"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { Plus, Pencil, Trash2, X, Wifi, WifiOff, Zap } from "lucide-react";

export default function RelaysPage() {
  const [relays, setRelays] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState({ url: "", priority: 0 });
  const [saving, setSaving] = useState(false);
  const [testResults, setTestResults] = useState<Record<string, boolean | null>>({});

  const loadRelays = async () => {
    try {
      const data = await api.getRelays();
      setRelays(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRelays();
  }, []);

  const openCreate = () => {
    setForm({ url: "", priority: 0 });
    setEditingId(null);
    setShowForm(true);
  };

  const openEdit = (relay: any) => {
    setForm({ url: relay.url, priority: relay.priority || 0 });
    setEditingId(relay.id);
    setShowForm(true);
  };

  const handleSave = async () => {
    if (!form.url.trim()) return;
    setSaving(true);
    setError("");
    try {
      if (editingId) {
        await api.updateRelay(editingId, form);
      } else {
        await api.addRelay(form);
      }
      setShowForm(false);
      setEditingId(null);
      await loadRelays();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this relay?")) return;
    try {
      await api.deleteRelay(id);
      await loadRelays();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const handleTest = async (id: string) => {
    setTestResults((prev) => ({ ...prev, [id]: null }));
    try {
      const result = await api.testRelay(id);
      setTestResults((prev) => ({ ...prev, [id]: result.success }));
    } catch {
      setTestResults((prev) => ({ ...prev, [id]: false }));
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading relays...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-on-surface">Relay Configuration</h1>
        <button
          onClick={openCreate}
          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity"
        >
          <Plus size={16} />
          Add Relay
        </button>
      </div>

      {error && <p className="text-error text-sm">{error}</p>}

      {showForm && (
        <div className="bg-surface-container-low rounded-xl p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-on-surface">
              {editingId ? "Edit Relay" : "Add Relay"}
            </h2>
            <button onClick={() => setShowForm(false)} className="text-on-surface/50 hover:text-on-surface">
              <X size={20} />
            </button>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <input
              placeholder="wss://relay.example.com"
              value={form.url}
              onChange={(e) => setForm({ ...form, url: e.target.value })}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40 md:col-span-2"
            />
            <input
              type="number"
              placeholder="Priority"
              value={form.priority}
              onChange={(e) => setForm({ ...form, priority: parseInt(e.target.value) || 0 })}
              className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-1 focus:ring-primary/40"
            />
          </div>
          <div className="flex gap-3 mt-4">
            <button
              onClick={handleSave}
              disabled={saving || !form.url.trim()}
              className="px-6 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save"}
            </button>
            <button
              onClick={() => setShowForm(false)}
              className="px-6 py-2 rounded-lg bg-surface-container-highest text-on-surface font-semibold text-sm hover:bg-surface-container-high transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="space-y-3">
        {relays.length === 0 ? (
          <p className="text-on-surface/50 text-sm">No relays configured.</p>
        ) : (
          relays.map((relay) => (
            <div
              key={relay.id}
              className="bg-surface-container-low rounded-xl p-6 flex items-center justify-between"
            >
              <div className="flex items-center gap-4">
                <div
                  className={cn(
                    "p-2 rounded-lg",
                    relay.active !== false
                      ? "bg-green-900/30 text-green-400"
                      : "bg-surface-container-highest text-on-surface/40"
                  )}
                >
                  {relay.active !== false ? <Wifi size={16} /> : <WifiOff size={16} />}
                </div>
                <div>
                  <p className="text-on-surface font-mono text-sm">{relay.url}</p>
                  <div className="flex items-center gap-3 mt-1">
                    <span className="text-on-surface/50 text-xs">
                      Priority: {relay.priority ?? 0}
                    </span>
                    {testResults[relay.id] !== undefined && (
                      <span
                        className={cn(
                          "rounded-full px-3 py-1 text-xs font-bold",
                          testResults[relay.id] === null
                            ? "bg-surface-container-highest text-on-surface/50"
                            : testResults[relay.id]
                              ? "bg-green-900/30 text-green-400"
                              : "bg-error-container/30 text-error"
                        )}
                      >
                        {testResults[relay.id] === null
                          ? "Testing..."
                          : testResults[relay.id]
                            ? "Connected"
                            : "Failed"}
                      </span>
                    )}
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => handleTest(relay.id)}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/60 hover:text-primary transition-colors"
                  title="Test connection"
                >
                  <Zap size={16} />
                </button>
                <button
                  onClick={() => openEdit(relay)}
                  className="p-2 rounded-lg hover:bg-surface-container-high text-on-surface/60 hover:text-on-surface transition-colors"
                >
                  <Pencil size={16} />
                </button>
                <button
                  onClick={() => handleDelete(relay.id)}
                  className="p-2 rounded-lg hover:bg-error-container/30 text-on-surface/60 hover:text-error transition-colors"
                >
                  <Trash2 size={16} />
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
