"use client";

import { useState, useEffect, useCallback } from "react";
import { Search, RefreshCw, BookOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SkillRow } from "@/components/skills/SkillRow";
import { AddSkillDialog } from "@/components/skills/AddSkillDialog";
import {
  fetchSkills,
  createSkill,
  updateSkill,
  deleteSkill,
  reloadSkills,
  uploadSkillZip,
  importSkillFromPath,
  type SkillInfo,
  type CreateSkillRequest,
} from "@/lib/api/skills";

export default function SkillsDashboard() {
  const [skills, setSkills] = useState<SkillInfo[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(false);

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

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

  const filteredSkills = skills.filter(
    (s) =>
      s.name.toLowerCase().includes(search.toLowerCase()) ||
      s.description.toLowerCase().includes(search.toLowerCase())
  );

  const handleAdd = async (req: CreateSkillRequest) => {
    await createSkill(req);
    await refresh();
  };

  const handleUploadZip = async (file: File) => {
    await uploadSkillZip(file);
    await refresh();
  };

  const handleImportPath = async (path: string) => {
    await importSkillFromPath(path);
    await refresh();
  };

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

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

  const handleReload = async () => {
    setLoading(true);
    try {
      await reloadSkills();
      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">Agent Skills</h1>
        </div>
        <p className="text-muted-foreground text-sm font-bold uppercase tracking-[0.1em] ml-6">
          Agent Skill 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 SKILL NAME OR DESCRIPTION..."
            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 Skills
          </Button>

          <AddSkillDialog onAdd={handleAdd} onUploadZip={handleUploadZip} onImportPath={handleImportPath} />
        </div>
      </div>

      <div className="relative border-2 border-border bg-card/30">
        {filteredSkills.map((skill) => (
          <SkillRow
            key={skill.name}
            skill={skill}
            onToggle={handleToggle}
            onDelete={handleDelete}
          />
        ))}
        {filteredSkills.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">
              <BookOpen 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 Skills Registered</p>
              <p className="text-[10px] text-muted-foreground/50 uppercase font-mono italic">
                Add an agent skill or place SKILL.md files in the skills/ directory.
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
