"use client";

import { useEffect, useState, useCallback } from "react";
import {
  Wifi,
  Server,
  RefreshCw,
  Cpu,
  Clock,
  MonitorSmartphone,
} from "lucide-react";
import { Button } from "@/components/ui/button";

interface LANNode {
  hostname: string;
  ip: string;
  port: number;
  version: string;
  gpu_summary: string;
  models: string[];
  latency_ms: number | null;
  last_seen: number;
}

interface LANNodesResponse {
  nodes: LANNode[];
  count: number;
  error?: string;
}

export default function LANNodesPage() {
  const [nodes, setNodes] = useState<LANNode[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);

  const fetchNodes = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/lan-nodes");
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data: LANNodesResponse = await res.json();
      if (data.error) {
        setError(data.error);
      }
      setNodes(data.nodes);
      setLastRefresh(new Date());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch nodes");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchNodes();
    // Auto-refresh every 15 seconds
    const interval = setInterval(fetchNodes, 15000);
    return () => clearInterval(interval);
  }, [fetchNodes]);

  const getStatusColor = (node: LANNode) => {
    if (node.latency_ms === null) return "bg-red-500";
    if (node.latency_ms < 10) return "bg-green-500";
    if (node.latency_ms < 50) return "bg-yellow-500";
    return "bg-orange-500";
  };

  const getLatencyLabel = (node: LANNode) => {
    if (node.latency_ms === null) return "Offline";
    return `${node.latency_ms.toFixed(0)}ms`;
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-100">LAN Nodes</h1>
          <p className="mt-1 text-sm text-gray-400">
            LLMHosts instances discovered on your local network via mDNS
          </p>
        </div>
        <div className="flex items-center gap-3">
          {lastRefresh && (
            <span className="text-xs text-gray-500">
              Updated {lastRefresh.toLocaleTimeString()}
            </span>
          )}
          <Button
            variant="secondary"
            size="sm"
            onClick={fetchNodes}
            disabled={loading}
          >
            <RefreshCw
              size={16}
              className={`mr-2 ${loading ? "animate-spin" : ""}`}
            />
            Refresh
          </Button>
        </div>
      </div>

      {/* Error banner */}
      {error && (
        <div className="rounded-lg border border-yellow-800/50 bg-yellow-900/20 p-4">
          <p className="text-sm text-yellow-400">
            {error === "zeroconf not installed"
              ? "LAN discovery requires the zeroconf package. Install with: pip install llmhosts[lan]"
              : error}
          </p>
        </div>
      )}

      {/* Summary cards */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-lg border border-gray-800 bg-gray-900 p-4">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-indigo-500/10 p-2">
              <Server size={20} className="text-indigo-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-100">{nodes.length}</p>
              <p className="text-xs text-gray-400">Nodes Discovered</p>
            </div>
          </div>
        </div>
        <div className="rounded-lg border border-gray-800 bg-gray-900 p-4">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-green-500/10 p-2">
              <Cpu size={20} className="text-green-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-100">
                {nodes.reduce((sum, n) => sum + n.models.length, 0)}
              </p>
              <p className="text-xs text-gray-400">Total Models</p>
            </div>
          </div>
        </div>
        <div className="rounded-lg border border-gray-800 bg-gray-900 p-4">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-cyan-500/10 p-2">
              <Wifi size={20} className="text-cyan-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-100">
                {nodes.filter((n) => n.latency_ms !== null).length}
              </p>
              <p className="text-xs text-gray-400">Online Nodes</p>
            </div>
          </div>
        </div>
      </div>

      {/* Node list */}
      {loading && nodes.length === 0 ? (
        <div className="flex items-center justify-center py-12">
          <RefreshCw size={24} className="animate-spin text-gray-500" />
          <span className="ml-3 text-gray-500">Scanning network...</span>
        </div>
      ) : nodes.length === 0 ? (
        <div className="rounded-lg border border-gray-800 bg-gray-900 p-8 text-center">
          <MonitorSmartphone
            size={48}
            className="mx-auto mb-4 text-gray-500"
          />
          <h3 className="text-lg font-medium text-gray-300">
            No nodes found
          </h3>
          <p className="mt-2 text-sm text-gray-500">
            Make sure other LLMHosts instances are running{" "}
            <code className="rounded bg-gray-800 px-1.5 py-0.5 text-xs">
              llmhosts serve
            </code>{" "}
            on the same network.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {nodes.map((node) => (
            <div
              key={`${node.ip}:${node.port}`}
              className="rounded-lg border border-gray-800 bg-gray-900 p-4 transition-colors hover:border-gray-700"
            >
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div
                    className={`h-3 w-3 rounded-full ${getStatusColor(node)}`}
                  />
                  <div>
                    <h3 className="font-semibold text-gray-100">
                      {node.hostname}
                    </h3>
                    <p className="text-sm text-gray-400">
                      {node.ip}:{node.port}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-4 text-sm">
                  <div className="flex items-center gap-1.5 text-gray-400">
                    <Clock size={14} />
                    <span
                      className={
                        node.latency_ms !== null
                          ? node.latency_ms < 10
                            ? "text-green-400"
                            : node.latency_ms < 50
                              ? "text-yellow-400"
                              : "text-orange-400"
                          : "text-red-400"
                      }
                    >
                      {getLatencyLabel(node)}
                    </span>
                  </div>
                  {node.version && (
                    <span className="text-gray-500">v{node.version}</span>
                  )}
                </div>
              </div>

              {/* GPU info */}
              {node.gpu_summary && (
                <div className="mt-3 flex items-center gap-2 text-sm text-gray-400">
                  <Cpu size={14} className="text-gray-500" />
                  <span>{node.gpu_summary}</span>
                </div>
              )}

              {/* Models */}
              {node.models.length > 0 && (
                <div className="mt-3">
                  <div className="flex flex-wrap gap-1.5">
                    {node.models.slice(0, 8).map((model) => (
                      <span
                        key={model}
                        className="rounded-full bg-gray-800 px-2.5 py-0.5 text-xs text-gray-300"
                      >
                        {model}
                      </span>
                    ))}
                    {node.models.length > 8 && (
                      <span className="rounded-full bg-gray-800 px-2.5 py-0.5 text-xs text-gray-500">
                        +{node.models.length - 8} more
                      </span>
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Topology diagram */}
      {nodes.length > 0 && (
        <div className="rounded-lg border border-gray-800 bg-gray-900 p-6">
          <h2 className="mb-4 text-lg font-semibold text-gray-100">
            LAN Topology
          </h2>
          <div className="flex flex-wrap items-center justify-center gap-6">
            {/* This node (center) */}
            <div className="flex flex-col items-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-indigo-500/20 ring-2 ring-indigo-500">
                <Server size={28} className="text-indigo-400" />
              </div>
              <span className="mt-2 text-xs font-medium text-indigo-400">
                This Node
              </span>
            </div>

            {/* Connection lines */}
            <div className="hidden items-center sm:flex">
              <div className="h-px w-12 bg-gray-700" />
              <Wifi size={16} className="mx-1 text-gray-500" />
              <div className="h-px w-12 bg-gray-700" />
            </div>

            {/* Discovered nodes */}
            <div className="flex flex-wrap items-center gap-4">
              {nodes.map((node) => (
                <div
                  key={`topo-${node.ip}:${node.port}`}
                  className="flex flex-col items-center"
                >
                  <div
                    className={`flex h-14 w-14 items-center justify-center rounded-full ${
                      node.latency_ms !== null
                        ? "bg-green-500/20 ring-2 ring-green-500/50"
                        : "bg-red-500/20 ring-2 ring-red-500/50"
                    }`}
                  >
                    <MonitorSmartphone
                      size={24}
                      className={
                        node.latency_ms !== null
                          ? "text-green-400"
                          : "text-red-400"
                      }
                    />
                  </div>
                  <span className="mt-1.5 max-w-[80px] truncate text-xs text-gray-400">
                    {node.hostname}
                  </span>
                  <span className="text-xs text-gray-500">
                    {node.models.length} models
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
