"use client";

import { useState } from "react";
import { BookOpen, Trash2, FileCode, FileText } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger, SheetDescription } from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
import type { SkillInfo, SkillDetail } from "@/lib/api/skills";
import { fetchSkillDetail } from "@/lib/api/skills";

type SkillRowProps = {
  skill: SkillInfo;
  onToggle: (name: string, enabled: boolean) => void;
  onDelete: (name: string) => void;
};

export function SkillRow({ skill, onToggle, onDelete }: SkillRowProps) {
  const [detail, setDetail] = useState<SkillDetail | null>(null);
  const [loadingDetail, setLoadingDetail] = useState(false);

  const handleOpenDetail = async () => {
    if (detail) return;
    setLoadingDetail(true);
    try {
      const d = await fetchSkillDetail(skill.name);
      setDetail(d);
    } catch {
      // silently fail
    } finally {
      setLoadingDetail(false);
    }
  };

  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",
        skill.enabled
          ? "bg-emerald-500 shadow-[0_0_6px_theme(colors.emerald.500)]"
          : "bg-zinc-500"
      )} />

      {/* Name + hover card */}
      <HoverCard openDelay={300} closeDelay={100}>
        <HoverCardTrigger asChild>
          <Sheet>
            <SheetTrigger asChild>
              <span
                className="font-bold text-sm text-foreground truncate cursor-pointer hover:text-primary transition-colors min-w-0 flex-shrink"
                onClick={handleOpenDetail}
              >
                {skill.name}
              </span>
            </SheetTrigger>
            <SheetContent className="bg-background/95 backdrop-blur-3xl border-l border-foreground/5 w-[500px] sm:w-[640px] 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">
                    <BookOpen className="w-6 h-6 text-primary-foreground" />
                  </div>
                  {skill.name}
                </SheetTitle>
                <SheetDescription className="text-foreground/40 font-medium uppercase tracking-[0.2em] text-[10px] pt-2">
                  Agent Skill Details
                </SheetDescription>
              </SheetHeader>

              <div className="space-y-8">
                <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-3">Description</h3>
                  <p className="text-sm text-foreground/70">{skill.description}</p>
                </div>

                {skill.scripts.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">
                      Scripts ({skill.scripts.length})
                    </h3>
                    <div className="space-y-2">
                      {skill.scripts.map((s) => (
                        <div key={s} className="flex items-center gap-2 text-xs font-mono text-foreground/70 p-2 rounded-xl bg-black/20">
                          <FileCode className="w-3.5 h-3.5 text-primary/60" />
                          {s}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {skill.references.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">
                      References ({skill.references.length})
                    </h3>
                    <div className="space-y-2">
                      {skill.references.map((r) => (
                        <div key={r} className="flex items-center gap-2 text-xs font-mono text-foreground/70 p-2 rounded-xl bg-black/20">
                          <FileText className="w-3.5 h-3.5 text-primary/60" />
                          {r}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="space-y-4">
                  <h3 className="text-[10px] font-black uppercase tracking-widest text-foreground/30 px-2">
                    SKILL.md Content
                  </h3>
                  <ScrollArea className="h-[400px]">
                    {loadingDetail ? (
                      <div className="p-4 text-center text-xs text-muted-foreground/40">Loading...</div>
                    ) : detail?.content ? (
                      <pre className="p-4 rounded-2xl border border-foreground/5 bg-black/30 text-xs font-mono text-foreground/60 whitespace-pre-wrap leading-relaxed">
                        {detail.content}
                      </pre>
                    ) : (
                      <div className="p-4 text-center text-xs text-muted-foreground/40 border border-dashed border-foreground/10 rounded-2xl">
                        No content loaded
                      </div>
                    )}
                  </ScrollArea>
                </div>
              </div>
            </SheetContent>
          </Sheet>
        </HoverCardTrigger>
        <HoverCardContent side="bottom" align="start" className="w-72 bg-popover/95 backdrop-blur-xl border-foreground/10">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <BookOpen className="w-4 h-4 text-primary" />
              <span className="font-black text-sm">{skill.name}</span>
            </div>
            {skill.description && (
              <p className="text-xs text-foreground/60 leading-relaxed">{skill.description}</p>
            )}
            {skill.scripts.length > 0 && (
              <div className="flex flex-wrap gap-1 pt-1">
                {skill.scripts.map((s) => (
                  <span key={s} className="text-[10px] font-mono px-2 py-0.5 bg-foreground/5 border border-foreground/10 text-foreground/60">
                    {s}
                  </span>
                ))}
              </div>
            )}
          </div>
        </HoverCardContent>
      </HoverCard>

      {/* Counts */}
      <span className="text-[10px] font-mono text-muted-foreground/60 shrink-0">
        {skill.scripts.length} scripts / {skill.references.length} refs
      </span>

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

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

      {/* Delete button - visible on hover */}
      <div className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
          onClick={() => onDelete(skill.name)}
          title="Delete"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </Button>
      </div>
    </div>
  );
}
