import { useState, useEffect } from "react";
import {
  Shield,
  Server,
  Activity,
  Plus,
  Power,
  RefreshCw,
  Trash2,
} from "lucide-react";
import { apiFetch } from "./api";

interface VpnNode {
  id: string;
  name: string;
  country_code: string;
  ip_address: string;
  port: number;
  status: string;
  current_load: number;
}

export default function AdminDashboard() {
  const [nodes, setNodes] = useState<VpnNode[]>([]);
  const [loading, setLoading] = useState(true);
  const [busyNodeId, setBusyNodeId] = useState<string | null>(null);

  const [name, setName] = useState("");
  const [ip, setIp] = useState("");
  const [code, setCode] = useState("de");
  const [sshPassword, setSshPassword] = useState("");
  const [sniDomain, setSniDomain] = useState("");
  const [publicKey, setPublicKey] = useState("");

  const fetchNodes = async () => {
    try {
      // /admin/nodes (не публичный /nodes) — админке нужно видеть все ноды,
      // включая "provisioning"/"offline", а не только "online".
      const res = await apiFetch("/admin/nodes");
      if (!res.ok) throw new Error("API Error");
      const data = await res.json();
      if (Array.isArray(data)) {
        setNodes(data);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    let isMounted = true;

    const loadData = async () => {
      if (isMounted) {
        await fetchNodes();
      }
    };

    loadData();

    return () => {
      isMounted = false;
    };
  }, []);

  const handleAddNode = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await apiFetch("/admin/nodes", {
        method: "POST",
        body: JSON.stringify({
          name,
          country_code: code,
          ip_address: ip,
          port: 443,
          ssh_password: sshPassword,
          public_key: publicKey || null,
          sni_domain: sniDomain || null,
        }),
      });
      if (res.ok) {
        setName("");
        setIp("");
        setSshPassword("");
        setSniDomain("");
        setPublicKey("");
        fetchNodes();
      } else {
        console.error("Failed to add node:", await res.text());
      }
    } catch (e) {
      console.error(e);
    }
  };

  const handleRestartNode = async (node: VpnNode) => {
    if (
      !window.confirm(
        `Force restart ${node.name}? Активные соединения на этой ноде оборвутся.`,
      )
    ) {
      return;
    }
    setBusyNodeId(node.id);
    try {
      const res = await apiFetch(`/admin/nodes/${node.id}/restart`, {
        method: "POST",
      });
      if (!res.ok) console.error("Failed to restart node:", await res.text());
      await fetchNodes();
    } catch (e) {
      console.error(e);
    } finally {
      setBusyNodeId(null);
    }
  };

  const handleDeleteNode = async (node: VpnNode) => {
    if (
      !window.confirm(
        `Удалить ноду ${node.name} безвозвратно? Это действие нельзя отменить.`,
      )
    ) {
      return;
    }
    setBusyNodeId(node.id);
    try {
      const res = await apiFetch(`/admin/nodes/${node.id}`, {
        method: "DELETE",
      });
      if (res.ok) {
        setNodes((prev) => prev.filter((n) => n.id !== node.id));
      } else {
        console.error("Failed to delete node:", await res.text());
      }
    } catch (e) {
      console.error(e);
    } finally {
      setBusyNodeId(null);
    }
  };

  return (
    <div className="min-h-screen bg-[#05050A] text-foreground font-mono p-6 sm:p-12">
      <header className="flex items-center justify-between mb-12 border-b border-white/10 pb-6">
        <div>
          <h1 className="text-2xl font-black tracking-widest text-primary flex items-center gap-3">
            <Shield className="w-6 h-6" />
            ORCHESTRATOR_NEXUS
          </h1>
          <p className="text-xs text-muted-foreground mt-2 uppercase tracking-widest">
            Netrunner Global Infrastructure Control
          </p>
        </div>
        <button
          onClick={fetchNodes}
          className="p-3 bg-white/5 hover:bg-white/10 rounded-full transition-colors"
        >
          <RefreshCw
            className={`w-5 h-5 text-secondary ${loading ? "animate-spin" : ""}`}
          />
        </button>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-1">
          <div className="bg-black/40 border border-white/10 rounded-2xl p-6 relative overflow-hidden group">
            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-secondary to-primary opacity-50" />
            <h2 className="text-sm font-bold uppercase tracking-widest mb-6 flex items-center gap-2">
              <Plus className="w-4 h-4 text-secondary" />
              Deploy New Node
            </h2>

            <form onSubmit={handleAddNode} className="space-y-4">
              <div>
                <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                  Designation
                </label>
                <input
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="e.g. Frankfurt Alpha"
                  className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                    IPv4 Address
                  </label>
                  <input
                    required
                    value={ip}
                    onChange={(e) => setIp(e.target.value)}
                    placeholder="147.x.x.x"
                    className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 font-mono"
                  />
                </div>
                <div>
                  <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                    Region (ISO)
                  </label>
                  <input
                    required
                    value={code}
                    onChange={(e) => setCode(e.target.value)}
                    placeholder="de"
                    className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 uppercase"
                  />
                </div>
              </div>

              <div>
                <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                  Root SSH Password (Temporary)
                </label>
                <input
                  required
                  type="password"
                  value={sshPassword}
                  onChange={(e) => setSshPassword(e.target.value)}
                  placeholder="••••••••"
                  className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 font-mono"
                />
              </div>

              <div>
                <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                  SNI Decoy Domain (optional)
                </label>
                <input
                  value={sniDomain}
                  onChange={(e) => setSniDomain(e.target.value)}
                  placeholder="cloudflare.com"
                  className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 font-mono"
                />
              </div>

              <div>
                <label className="text-[10px] text-muted-foreground uppercase tracking-widest">
                  Public Key (optional)
                </label>
                <input
                  value={publicKey}
                  onChange={(e) => setPublicKey(e.target.value)}
                  placeholder="node identity public key"
                  className="w-full bg-white/5 border border-white/10 rounded-lg p-3 text-sm focus:border-secondary outline-none transition-colors mt-1 font-mono"
                />
              </div>

              <button
                type="submit"
                className="w-full mt-4 bg-secondary/10 hover:bg-secondary/20 text-secondary border border-secondary/30 font-bold uppercase tracking-widest text-xs py-3 rounded-lg transition-all flex items-center justify-center gap-2"
              >
                <Server className="w-4 h-4" /> Initialize Node
              </button>
            </form>
          </div>
        </div>

        <div className="lg:col-span-2 space-y-4">
          <h2 className="text-sm font-bold uppercase tracking-widest text-muted-foreground mb-4">
            Active Grid
          </h2>

          {nodes.map((node) => (
            <div
              key={node.id}
              className="bg-black/60 border border-white/5 rounded-2xl p-5 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 hover:border-primary/30 transition-colors"
            >
              <div>
                <div className="flex items-center gap-3 mb-1">
                  <div
                    className={`w-2 h-2 rounded-full ${
                      node.status === "online"
                        ? "bg-green-500 animate-pulse"
                        : node.status === "provisioning"
                          ? "bg-yellow-500 animate-pulse"
                          : "bg-red-500"
                    }`}
                  />
                  <h3 className="font-bold text-lg">{node.name}</h3>
                  <span className="text-[10px] bg-white/10 px-2 py-0.5 rounded text-muted-foreground uppercase">
                    {node.country_code}
                  </span>
                </div>
                <p className="text-xs text-muted-foreground font-mono">
                  {node.ip_address}:{node.port}
                </p>
              </div>

              <div className="flex items-center gap-6 w-full sm:w-auto">
                <div className="flex-1 sm:flex-none">
                  <p className="text-[10px] text-muted-foreground uppercase tracking-widest mb-1 flex items-center gap-1">
                    <Activity className="w-3 h-3" /> Load
                  </p>
                  <div className="w-full sm:w-32 h-2 bg-white/10 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-primary"
                      style={{ width: `${node.current_load}%` }}
                    />
                  </div>
                </div>
                <button
                  onClick={() => handleRestartNode(node)}
                  disabled={busyNodeId === node.id}
                  className="p-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 border border-red-500/20 rounded-lg transition-colors disabled:opacity-40"
                  title="Force Restart"
                >
                  <Power className="w-4 h-4" />
                </button>
                <button
                  onClick={() => handleDeleteNode(node)}
                  disabled={busyNodeId === node.id}
                  className="p-2 bg-white/5 hover:bg-red-500/20 text-muted-foreground hover:text-red-500 border border-white/10 hover:border-red-500/20 rounded-lg transition-colors disabled:opacity-40"
                  title="Terminate Node"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>
          ))}

          {nodes.length === 0 && !loading && (
            <div className="text-center p-12 border border-dashed border-white/10 rounded-2xl text-muted-foreground text-sm uppercase tracking-widest">
              No active nodes in the grid
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
