"use client";

import { useState } from "react";
import { BookOpen, Trash2, FileCode, FileText } 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 { 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 SkillCardProps = {
  skill: SkillInfo;
  onToggle: (name: string, enabled: boolean) => void;
  onDelete: (name: string) => void;
};

export function SkillCard({ skill, onToggle, onDelete }: SkillCardProps) {
  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 (
    <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={cn(
            "px-4 py-1.5 text-[9px] font-black uppercase tracking-[0.2em] rounded-full border transition-colors",
            skill.enabled
              ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-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",
                skill.enabled
                  ? "bg-emerald-500 shadow-[0_0_8px_theme(colors.emerald.500)]"
                  : "bg-zinc-500"
              )} />
              {skill.enabled ? "Active" : "Disabled"}
            </span>
          </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(skill.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">
            <BookOpen className="w-5 h-5 text-primary" />
          </div>
          <span className="group-hover:text-primary transition-colors truncate">{skill.name}</span>
        </CardTitle>
        <CardDescription className="text-xs font-medium text-muted-foreground leading-relaxed mt-2 px-1 line-clamp-2">
          {skill.description}
        </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">
                {skill.enabled ? "Enabled" : "Disabled"}
              </span>
            </div>
            <Switch
              checked={skill.enabled}
              onCheckedChange={(checked) => onToggle(skill.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 flex items-center gap-1">
                <FileCode className="w-3 h-3" /> Scripts
              </span>
              <span className="text-lg font-black text-primary">{skill.scripts.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 flex items-center gap-1">
                <FileText className="w-3 h-3" /> References
              </span>
              <span className="text-lg font-black text-primary">{skill.references.length}</span>
            </div>
          </div>
        </div>
      </CardContent>

      <CardFooter className="pt-2 pb-8 px-6">
        <Sheet>
          <SheetTrigger asChild>
            <Button
              variant="outline"
              className="w-full h-12 rounded-2xl border-foreground/10 font-bold uppercase tracking-widest hover:bg-foreground/10 transition-all"
              onClick={handleOpenDetail}
            >
              <BookOpen className="w-4 h-4 mr-2" />
              View SKILL.md
            </Button>
          </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">
              {/* Description */}
              <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>

              {/* Scripts */}
              {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>
              )}

              {/* References */}
              {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>
              )}

              {/* SKILL.md Content */}
              <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>
      </CardFooter>
    </Card>
  );
}
