"use client";

import { Server, Trash2, RotateCw, Power, PowerOff, Terminal, Globe, Radio, Settings2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { cn } from "@/lib/utils";
import type { MCPServerInfo } from "@/lib/api/mcp";

type MCPServerRowProps = {
  server: MCPServerInfo;
  onToggle: (name: string, enabled: boolean) => void;
  onConnect: (name: string) => void;
  onDisconnect: (name: string) => void;
  onRestart: (name: string) => void;
  onDelete: (name: string) => void;
  onEdit: (server: MCPServerInfo) => void;
};

const transportIcon = {
  stdio: Terminal,
  sse: Radio,
  "streamable-http": Globe,
};

const statusColor: Record<string, string> = {
  connected: "bg-emerald-500 shadow-[0_0_6px_theme(colors.emerald.500)]",
  disconnected: "bg-zinc-500",
  connecting: "bg-amber-500 animate-pulse shadow-[0_0_6px_theme(colors.amber.500)]",
  error: "bg-red-500 shadow-[0_0_6px_theme(colors.red.500)]",
};

export function MCPServerRow({ server, onToggle, onConnect, onDisconnect, onRestart, onDelete, onEdit }: MCPServerRowProps) {
  const TransportIcon = transportIcon[server.config.transport] || Globe;
  const isConnected = server.status === "connected";

  return (
    <div className="group flex items-center gap-4 px-5 py-3.5 border-b border-foreground/5 hover:bg-foreground/[0.03] transition-colors">
      {/* Status dot */}
      <div className={cn("w-2 h-2 rounded-full shrink-0", statusColor[server.status])} />

      {/* Name + hover card */}
      <HoverCard openDelay={300} closeDelay={100}>
        <HoverCardTrigger asChild>
          <span className="font-bold text-sm text-foreground truncate cursor-default min-w-0 flex-shrink">
            {server.name}
          </span>
        </HoverCardTrigger>
        <HoverCardContent side="bottom" align="start" className="w-80 bg-popover/95 backdrop-blur-xl border-foreground/10">
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Server className="w-4 h-4 text-primary" />
              <span className="font-black text-sm">{server.name}</span>
            </div>
            <div className="text-[10px] font-black uppercase tracking-widest text-primary">Connection</div>
            <code className="text-xs font-mono text-foreground/70 break-all bg-black/20 p-3 block border border-foreground/5">
              {server.config.transport === "stdio"
                ? `${server.config.command} ${(server.config.args || []).join(" ")}`
                : server.config.url || "\u2014"}
            </code>
            {server.config.env && Object.keys(server.config.env).length > 0 && (
              <>
                <div className="text-[10px] font-black uppercase tracking-widest text-primary">Environment</div>
                <div className="space-y-1">
                  {Object.entries(server.config.env).map(([k, v]) => (
                    <div key={k} className="flex gap-1.5 text-[11px] font-mono">
                      <span className="text-primary/80">{k}</span>
                      <span className="text-foreground/30">=</span>
                      <span className="text-foreground/50 truncate">{v}</span>
                    </div>
                  ))}
                </div>
              </>
            )}
            {server.tools.length > 0 && (
              <>
                <div className="text-[10px] font-black uppercase tracking-widest text-primary">
                  Tools ({server.tools.length})
                </div>
                <div className="flex flex-wrap gap-1">
                  {server.tools.map((tool) => (
                    <span key={tool.name} className="text-[10px] font-mono px-2 py-0.5 bg-foreground/5 border border-foreground/10 text-foreground/60">
                      {tool.name}
                    </span>
                  ))}
                </div>
              </>
            )}
            {server.error && (
              <div className="p-2 bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-mono break-all">
                {server.error}
              </div>
            )}
          </div>
        </HoverCardContent>
      </HoverCard>

      {/* Transport badge */}
      <Badge variant="outline" className="text-[9px] font-mono uppercase tracking-wider border-foreground/10 text-muted-foreground shrink-0 h-6">
        <TransportIcon className="w-3 h-3 mr-1" />
        {server.config.transport}
      </Badge>

      {/* Tools count */}
      <span className="text-[10px] font-mono text-muted-foreground/60 shrink-0">
        {server.tools.length} tools
      </span>

      {/* Spacer */}
      <div className="flex-1" />

      {/* Toggle */}
      <Switch
        checked={server.config.enabled}
        onCheckedChange={(checked) => onToggle(server.name, checked)}
        className="data-[state=checked]:bg-primary shrink-0"
      />

      {/* Action buttons - visible on hover */}
      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
        {isConnected ? (
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-muted-foreground hover:text-red-400 hover:bg-red-500/10"
            onClick={() => onDisconnect(server.name)}
            title="Disconnect"
          >
            <PowerOff className="w-3.5 h-3.5" />
          </Button>
        ) : (
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-muted-foreground hover:text-emerald-400 hover:bg-emerald-500/10"
            onClick={() => onConnect(server.name)}
            disabled={!server.config.enabled}
            title="Connect"
          >
            <Power className="w-3.5 h-3.5" />
          </Button>
        )}
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-foreground hover:bg-foreground/10"
          onClick={() => onEdit(server)}
          title="Edit Config"
        >
          <Settings2 className="w-3.5 h-3.5" />
        </Button>
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-primary hover:bg-primary/10"
          onClick={() => onRestart(server.name)}
          title="Restart"
        >
          <RotateCw className="w-3.5 h-3.5" />
        </Button>
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
          onClick={() => onDelete(server.name)}
          title="Delete"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </Button>
      </div>
    </div>
  );
}
