"use client";

import { useState, useEffect, useCallback } from "react";
import { Search, RefreshCw, Server } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { MCPServerRow } from "@/components/mcp/MCPServerRow";
import { AddServerDialog } from "@/components/mcp/AddServerDialog";
import { EditServerDialog } from "@/components/mcp/EditServerDialog";
import {
  fetchMCPServers,
  addMCPServer,
  updateMCPServer,
  deleteMCPServer,
  connectServer,
  disconnectServer,
  restartServer,
  reloadMCPConfig,
  type MCPServerInfo,
  type MCPServerConfig,
} from "@/lib/api/mcp";

export default function MCPDashboard() {
  const [servers, setServers] = useState<MCPServerInfo[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(false);
  const [editServer, setEditServer] = useState<MCPServerInfo | null>(null);
  const [editOpen, setEditOpen] = useState(false);

  const refresh = useCallback(async () => {
    try {
      const data = await fetchMCPServers();
      setServers(data);
    } catch (err) {
      console.error("Failed to fetch servers:", err);
    }
  }, []);

  useEffect(() => {
    refresh();
    const interval = setInterval(refresh, 5000);
    return () => clearInterval(interval);
  }, [refresh]);

  const filteredServers = servers.filter(
    (s) =>
      s.name.toLowerCase().includes(search.toLowerCase()) ||
      s.config.transport.toLowerCase().includes(search.toLowerCase())
  );

  const handleAdd = async (name: string, config: MCPServerConfig) => {
    await addMCPServer(name, config);
    await refresh();
  };

  const handleToggle = async (name: string, enabled: boolean) => {
    await updateMCPServer(name, { enabled });
    await refresh();
  };

  const handleConnect = async (name: string) => {
    await connectServer(name);
    await refresh();
  };

  const handleDisconnect = async (name: string) => {
    await disconnectServer(name);
    await refresh();
  };

  const handleRestart = async (name: string) => {
    await restartServer(name);
    await refresh();
  };

  const handleDelete = async (name: string) => {
    await deleteMCPServer(name);
    await refresh();
  };

  const handleEdit = (server: MCPServerInfo) => {
    setEditServer(server);
    setEditOpen(true);
  };

  const handleEditSave = async (name: string, config: Partial<MCPServerConfig>, restart: boolean) => {
    await updateMCPServer(name, config);
    if (restart) await restartServer(name);
    await refresh();
  };

  const handleReload = async () => {
    setLoading(true);
    try {
      await reloadMCPConfig();
      await refresh();
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-full overflow-y-auto p-10 space-y-12 bg-background relative">
      <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />

      <div className="relative flex flex-col gap-4">
        <div className="flex items-center gap-4">
          <div className="w-2 h-10 bg-primary" />
          <h1 className="text-4xl font-black uppercase tracking-tighter text-foreground">MCP Servers</h1>
        </div>
        <p className="text-muted-foreground text-sm font-bold uppercase tracking-[0.1em] ml-6">
          Model Context Protocol Server Registry & Management
        </p>
      </div>

      <div className="relative flex items-center justify-between gap-6 bg-card/50 p-6 border-2 border-border shadow-sm">
        <div className="relative flex-1 max-w-xl">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-primary" />
          <Input
            placeholder="SEARCH SERVER NAME OR TRANSPORT..."
            className="pl-12 h-12 rounded-none bg-background border-2 border-border focus-visible:ring-primary focus-visible:border-primary font-mono text-xs uppercase"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>

        <div className="flex gap-4">
          <Button
            variant="outline"
            className="h-12 rounded-none border-2 px-6 flex gap-3 font-black uppercase tracking-widest hover:bg-secondary/10 transition-all"
            onClick={handleReload}
            disabled={loading}
          >
            <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
            Reload Config
          </Button>

          <AddServerDialog onAdd={handleAdd} />
        </div>
      </div>

      <div className="relative border-2 border-border bg-card/30">
        {filteredServers.map((server) => (
          <MCPServerRow
            key={server.name}
            server={server}
            onToggle={handleToggle}
            onConnect={handleConnect}
            onDisconnect={handleDisconnect}
            onRestart={handleRestart}
            onDelete={handleDelete}
            onEdit={handleEdit}
          />
        ))}
        {filteredServers.length === 0 && (
          <div className="py-24 text-center flex flex-col items-center gap-4">
            <div className="p-4 bg-muted/20 border border-muted/30">
              <Server className="w-10 h-10 text-muted-foreground/30" />
            </div>
            <div className="space-y-1">
              <p className="text-muted-foreground font-bold uppercase tracking-widest">No Servers Registered</p>
              <p className="text-[10px] text-muted-foreground/50 uppercase font-mono italic">
                Add an MCP server to get started.
              </p>
            </div>
          </div>
        )}
      </div>

      <EditServerDialog
        server={editServer}
        open={editOpen}
        onOpenChange={setEditOpen}
        onSave={handleEditSave}
      />
    </div>
  );
}
