"use client";

import { Server, Trash2, RotateCw, Power, PowerOff, Terminal, Globe, Radio } from "lucide-react";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger, SheetDescription } from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
import type { MCPServerInfo } from "@/lib/api/mcp";

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

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

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

const statusLabel: Record<string, string> = {
  connected: "Connected",
  disconnected: "Offline",
  connecting: "Connecting",
  error: "Error",
};

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

  return (
    <Card className="relative group overflow-hidden border border-foreground/5 bg-foreground/5 backdrop-blur-xl transition-all duration-500 hover:border-primary/30 hover:bg-foreground/10 hover:shadow-[0_20px_50px_rgba(0,0,0,0.3)] rounded-[2rem]">
      <div className="absolute -top-24 -right-24 w-48 h-48 bg-primary/10 blur-[60px] rounded-full group-hover:bg-primary/20 transition-colors duration-700" />

      <CardHeader className="relative pb-2">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className={cn(
              "px-4 py-1.5 text-[9px] font-black uppercase tracking-[0.2em] rounded-full border transition-colors",
              isConnected
                ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400"
                : server.status === "error"
                  ? "bg-red-500/10 border-red-500/20 text-red-400"
                  : "bg-foreground/5 border-foreground/10 text-muted-foreground"
            )}>
              <span className="flex items-center gap-2">
                <div className={cn("w-1.5 h-1.5 rounded-full", statusColor[server.status])} />
                {statusLabel[server.status]}
              </span>
            </div>
            <Badge variant="outline" className="text-[9px] font-mono uppercase tracking-widest border-foreground/10 text-muted-foreground">
              <TransportIcon className="w-3 h-3 mr-1" />
              {server.config.transport}
            </Badge>
          </div>

          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9 rounded-full text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
            onClick={() => onDelete(server.name)}
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>

        <CardTitle className="text-xl font-black tracking-tight flex items-center gap-4">
          <div className="p-3 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:border-primary/30 transition-colors">
            <Server className="w-5 h-5 text-primary" />
          </div>
          <span className="group-hover:text-primary transition-colors truncate">{server.name}</span>
        </CardTitle>
        <CardDescription className="text-xs font-medium text-muted-foreground leading-relaxed mt-2 px-1">
          {server.config.transport === "stdio"
            ? `${server.config.command} ${(server.config.args || []).join(" ")}`
            : server.config.url || "—"}
        </CardDescription>
      </CardHeader>

      <CardContent className="pt-4 relative">
        <div className="space-y-4">
          <div className="flex items-center justify-between p-4 bg-foreground/5 rounded-2xl border border-foreground/5 group-hover:border-foreground/10 transition-colors">
            <div className="flex flex-col">
              <span className="text-[9px] font-black uppercase tracking-widest text-muted-foreground">Power</span>
              <span className="text-[10px] font-bold text-foreground/70 uppercase tracking-tighter">
                {server.config.enabled ? "Enabled" : "Disabled"}
              </span>
            </div>
            <Switch
              checked={server.config.enabled}
              onCheckedChange={(checked) => onToggle(server.name, checked)}
              className="data-[state=checked]:bg-primary"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="p-4 rounded-2xl border border-foreground/5 bg-foreground/5 flex flex-col gap-1">
              <span className="text-[8px] uppercase font-bold text-muted-foreground/40 tracking-widest">Tools</span>
              <span className="text-lg font-black text-primary">{server.tools.length}</span>
            </div>
            <div className="p-4 rounded-2xl border border-foreground/5 bg-foreground/5 flex flex-col gap-1">
              <span className="text-[8px] uppercase font-bold text-muted-foreground/40 tracking-widest">Transport</span>
              <span className="text-[10px] font-mono font-bold text-foreground/80 uppercase">{server.config.transport}</span>
            </div>
          </div>

          {server.error && (
            <div className="p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-mono break-all">
              {server.error}
            </div>
          )}
        </div>
      </CardContent>

      <CardFooter className="pt-2 pb-8 px-6 flex gap-3">
        {isConnected ? (
          <Button
            variant="outline"
            className="flex-1 h-12 rounded-2xl border-foreground/10 font-bold uppercase tracking-widest hover:bg-red-500/10 hover:text-red-400 hover:border-red-500/20 transition-all"
            onClick={() => onDisconnect(server.name)}
          >
            <PowerOff className="w-4 h-4 mr-2" />
            Disconnect
          </Button>
        ) : (
          <Button
            className="flex-1 h-12 rounded-2xl bg-primary text-primary-foreground font-bold uppercase tracking-widest hover:opacity-90 transition-all"
            onClick={() => onConnect(server.name)}
            disabled={!server.config.enabled}
          >
            <Power className="w-4 h-4 mr-2" />
            Connect
          </Button>
        )}

        <Sheet>
          <SheetTrigger asChild>
            <Button
              variant="outline"
              className="h-12 rounded-2xl border-foreground/10 font-bold uppercase tracking-widest hover:bg-foreground/10 transition-all px-5"
            >
              <RotateCw className="w-4 h-4" />
            </Button>
          </SheetTrigger>
          <SheetContent className="bg-background/95 backdrop-blur-3xl border-l border-foreground/5 w-[400px] sm:w-[540px] text-foreground overflow-y-auto">
            <SheetHeader className="border-b border-foreground/5 pb-8 mb-8">
              <SheetTitle className="text-3xl font-black uppercase tracking-tighter text-foreground flex items-center gap-4">
                <div className="p-3 bg-primary rounded-2xl ring-4 ring-primary/10 shadow-2xl">
                  <Server className="w-6 h-6 text-primary-foreground" />
                </div>
                {server.name}
              </SheetTitle>
              <SheetDescription className="text-foreground/40 font-medium uppercase tracking-[0.2em] text-[10px] pt-2">
                MCP Server Details &bull; {server.config.transport.toUpperCase()}
              </SheetDescription>
            </SheetHeader>

            <div className="space-y-8">
              {/* Connection info */}
              <div className="p-6 rounded-3xl border border-foreground/5 bg-foreground/5 relative overflow-hidden">
                <div className="absolute top-0 right-0 w-24 h-24 bg-primary/5 blur-3xl rounded-full" />
                <h3 className="text-[10px] font-black uppercase tracking-widest text-primary mb-4">Connection</h3>
                {server.config.transport === "stdio" ? (
                  <code className="text-xs font-mono text-foreground/70 break-all bg-black/40 p-4 block rounded-2xl border border-foreground/5">
                    {server.config.command} {(server.config.args || []).join(" ")}
                  </code>
                ) : (
                  <code className="text-xs font-mono text-foreground/70 break-all bg-black/40 p-4 block rounded-2xl border border-foreground/5">
                    {server.config.url}
                  </code>
                )}
              </div>

              {/* Env vars */}
              {server.config.env && Object.keys(server.config.env).length > 0 && (
                <div className="p-6 rounded-3xl border border-foreground/5 bg-foreground/5">
                  <h3 className="text-[10px] font-black uppercase tracking-widest text-primary mb-4">Environment</h3>
                  <div className="space-y-2">
                    {Object.entries(server.config.env).map(([k, v]) => (
                      <div key={k} className="flex gap-2 text-xs font-mono">
                        <span className="text-primary/80">{k}</span>
                        <span className="text-foreground/30">=</span>
                        <span className="text-foreground/60 truncate">{v}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Tools list */}
              <div className="space-y-4">
                <h3 className="text-[10px] font-black uppercase tracking-widest text-foreground/30 px-2">
                  Tools ({server.tools.length})
                </h3>
                {server.tools.length > 0 ? (
                  <div className="space-y-3">
                    {server.tools.map((tool) => (
                      <div key={tool.name} className="p-4 rounded-2xl border border-foreground/5 bg-foreground/5">
                        <div className="text-sm font-bold text-foreground">{tool.name}</div>
                        {tool.description && (
                          <div className="text-xs text-foreground/50 mt-1">{tool.description}</div>
                        )}
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="p-4 text-center text-xs text-muted-foreground/40 border border-dashed border-foreground/10 rounded-2xl">
                    {isConnected ? "No tools available" : "Connect to see tools"}
                  </div>
                )}
              </div>

              {/* Actions */}
              <div className="pt-4 space-y-3">
                <Button
                  className="w-full h-14 bg-primary text-primary-foreground font-black uppercase tracking-[0.2em] rounded-2xl shadow-2xl shadow-primary/20 hover:scale-[1.02] active:scale-95 transition-all"
                  onClick={() => onRestart(server.name)}
                >
                  <RotateCw className="w-4 h-4 mr-2" />
                  Restart Server
                </Button>
              </div>
            </div>
          </SheetContent>
        </Sheet>
      </CardFooter>
    </Card>
  );
}
