"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { aiAgentApi } from "@/lib/api/aiAgent";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Bot, Plus, Search, Pencil, Trash2, Loader2, FileText, Upload, X, Settings2 } from "lucide-react";
import { toast } from "sonner";

const MODEL_GROUPS = [
  { provider: "Anthropic", color: "#D97757", models: [
    { value: "claude-opus-4-20250514", label: "Claude Opus 4" },
    { value: "claude-sonnet-4-20250514", label: "Claude Sonnet 4" },
    { value: "claude-haiku-4-20250514", label: "Claude Haiku 4" },
    { value: "claude-sonnet-4-5-20250514", label: "Claude Sonnet 4.5" },
  ]},
  { provider: "OpenAI", color: "#10A37F", models: [
    { value: "gpt-4o", label: "GPT-4o" },
    { value: "gpt-4o-mini", label: "GPT-4o Mini" },
    { value: "o1", label: "o1" },
    { value: "o3-mini", label: "o3 Mini" },
  ]},
  { provider: "Google", color: "#4285F4", models: [
    { value: "gemini-2.5-pro", label: "Gemini 2.5 Pro" },
    { value: "gemini-2.5-flash", label: "Gemini 2.5 Flash" },
    { value: "gemini-2.0-flash", label: "Gemini 2.0 Flash (무료)" },
  ]},
  { provider: "DeepSeek", color: "#0066FF", models: [
    { value: "deepseek-chat", label: "DeepSeek Chat (V3)" },
    { value: "deepseek-reasoner", label: "DeepSeek Reasoner (R1)" },
  ]},
  { provider: "Ollama (로컬)", color: "#1D1D1D", models: [
    { value: "llama3.2", label: "Llama 3.2" },
    { value: "mistral", label: "Mistral" },
    { value: "qwen2.5", label: "Qwen 2.5" },
  ]},
];

function getModelColor(model: string): string {
  for (const g of MODEL_GROUPS) { if (g.models.some((m) => m.value === model)) return g.color; }
  return "#6B7280";
}
function getModelLabel(model: string): string {
  for (const g of MODEL_GROUPS) { const m = g.models.find((m) => m.value === model); if (m) return m.label; }
  return model;
}

interface Agent {
  id: number; agent_id: string; name: string; description?: string; model: string;
  system_prompt?: string; config: Record<string, any>; status: string; created_at: string;
}

interface AgentForm {
  name: string; description: string; model: string; system_prompt: string;
  config: { temperature: number; max_tokens: number; knowledge_files: Array<{ name: string; content: string }> };
}

const DEFAULT_FORM: AgentForm = {
  name: "", description: "", model: "claude-sonnet-4-20250514", system_prompt: "",
  config: { temperature: 0.7, max_tokens: 4096, knowledge_files: [] },
};

export default function AgentListPage() {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Agent | null>(null);
  const [form, setForm] = useState<AgentForm>({ ...DEFAULT_FORM });
  const [saving, setSaving] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [libraryFiles, setLibraryFiles] = useState<any[]>([]);
  const [libraryLoading, setLibraryLoading] = useState(false);

  const loadLibrary = useCallback(async () => {
    setLibraryLoading(true);
    try { const res = await aiAgentApi.listKnowledge(); setLibraryFiles(res.data || []); }
    catch { /* 라이브러리 없어도 무시 */ }
    setLibraryLoading(false);
  }, []);

  const loadAgents = useCallback(async () => {
    setLoading(true);
    try { const res = await aiAgentApi.list({ search: search || undefined }); setAgents(res.data || []); }
    catch { toast.error("에이전트 목록 로드 실패"); }
    setLoading(false);
  }, [search]);

  useEffect(() => { loadAgents(); }, [loadAgents]);

  const openCreate = () => {
    setEditing(null);
    setForm({ ...DEFAULT_FORM, config: { ...DEFAULT_FORM.config, knowledge_files: [] } });
    loadLibrary();
    setModalOpen(true);
  };

  const openEdit = (agent: Agent) => {
    setEditing(agent);
    const cfg = agent.config || {};
    setForm({
      name: agent.name, description: agent.description || "", model: agent.model,
      system_prompt: agent.system_prompt || "",
      config: { temperature: cfg.temperature ?? 0.7, max_tokens: cfg.max_tokens ?? 4096, knowledge_files: cfg.knowledge_files || [] },
    });
    loadLibrary();
    setModalOpen(true);
  };

  const addLibraryFile = async (libFile: any) => {
    try {
      const res = await aiAgentApi.getKnowledge(libFile.id);
      const file = res.data;
      const alreadyExists = form.config.knowledge_files.some((f) => f.name === file.name);
      if (alreadyExists) { toast.error("이미 추가된 파일입니다."); return; }
      setForm((prev) => ({
        ...prev,
        config: {
          ...prev.config,
          knowledge_files: [...prev.config.knowledge_files, { name: file.name, content: file.content, source: "library", library_id: file.id }],
        },
      }));
      toast.success(`${file.name} 추가됨`);
    } catch { toast.error("파일 불러오기 실패"); }
  };

  const handleSave = async () => {
    if (!form.name) { toast.error("에이전트 이름은 필수입니다."); return; }
    setSaving(true);
    try {
      if (editing) { await aiAgentApi.update(editing.id, form); toast.success("수정 완료"); }
      else { await aiAgentApi.create({ ...form, agent_id: `agent-${crypto.randomUUID().split("-")[0]}` }); toast.success("생성 완료"); }
      setModalOpen(false); loadAgents();
    } catch (e: any) { toast.error(e.response?.data?.message || "저장 실패"); }
    setSaving(false);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("에이전트를 삭제하시겠습니까?")) return;
    try { await aiAgentApi.delete(id); toast.success("삭제 완료"); loadAgents(); }
    catch { toast.error("삭제 실패"); }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;
    Array.from(files).forEach((file) => {
      const reader = new FileReader();
      reader.onload = async (ev) => {
        const content = (ev.target?.result as string).substring(0, 50000);
        const fileName = file.name;
        const name = fileName.replace(/\.[^.]+$/, "");

        try {
          const libRes = await aiAgentApi.createKnowledge({
            name,
            file_name: fileName,
            category: "공통",
            description: `${editing?.name || form.name || "에이전트"} 설정에서 업로드`,
            content,
          });
          const libraryId = libRes.data?.id;

          setForm((prev) => ({
            ...prev,
            config: {
              ...prev.config,
              knowledge_files: [...prev.config.knowledge_files, { name, content, source: "library", library_id: libraryId }],
            },
          }));
          toast.success(`${fileName} → 라이브러리 등록 + 에이전트 적용`);
          loadLibrary();
        } catch {
          setForm((prev) => ({
            ...prev,
            config: { ...prev.config, knowledge_files: [...prev.config.knowledge_files, { name, content }] },
          }));
          toast.success(`${fileName} 추가됨 (라이브러리 등록은 실패)`);
        }
      };
      reader.readAsText(file);
    });
    e.target.value = "";
  };

  const removeFile = (idx: number) => {
    setForm((prev) => ({ ...prev, config: { ...prev.config, knowledge_files: prev.config.knowledge_files.filter((_, i) => i !== idx) } }));
  };

  return (
    <div className="h-full overflow-y-auto bg-background">
      <div className="space-y-4 p-4 sm:p-5">
        <div className="flex items-center justify-between border-b pb-3">
          <div>
            <h1 className="text-lg font-bold tracking-tight">AI 에이전트</h1>
            <p className="mt-0.5 text-xs text-muted-foreground">모델 선택, 프롬프트, 지식 파일을 설정합니다. 데이터 연결은 워크스페이스에서 합니다.</p>
          </div>
          <Button onClick={openCreate} size="sm" className="h-8 gap-1 text-xs"><Plus className="h-3.5 w-3.5" />에이전트 추가</Button>
        </div>

        <div className="relative w-56">
          <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder="검색..." value={search} onChange={(e) => setSearch(e.target.value)} className="h-8 pl-8 text-xs" />
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-16"><Loader2 className="h-5 w-5 animate-spin" /></div>
        ) : agents.length === 0 ? (
          <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-16">
            <Bot className="mb-2 h-5 w-5 text-muted-foreground" />
            <p className="text-xs text-muted-foreground">등록된 에이전트가 없습니다</p>
          </div>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {agents.map((agent) => {
              const color = getModelColor(agent.model);
              const cfg = agent.config || {};
              const fileCount = (cfg.knowledge_files || []).length;
              return (
                <div key={agent.id} className="group flex flex-col rounded-lg border bg-card p-3.5 transition-all hover:shadow-md hover:border-primary/30">
                  <div className="mb-2 flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      <div className="flex h-7 w-7 items-center justify-center rounded-md" style={{ backgroundColor: `${color}15` }}>
                        <Bot className="h-4 w-4" style={{ color }} />
                      </div>
                      <div>
                        <p className="text-xs font-semibold">{agent.name}</p>
                        <p className="text-[10px] text-muted-foreground font-mono">{agent.agent_id}</p>
                      </div>
                    </div>
                    <Badge variant={agent.status === "active" ? "default" : "secondary"} className="h-5 text-[9px]">{agent.status}</Badge>
                  </div>
                  <p className="mb-2 min-h-[28px] text-[10px] text-muted-foreground line-clamp-2">{agent.description || ""}</p>
                  <div className="mb-2 rounded-md bg-muted/50 px-2 py-1.5">
                    <div className="flex items-center gap-1.5">
                      <span className="h-2 w-2 rounded-full" style={{ backgroundColor: color }} />
                      <span className="text-[10px] font-medium">{getModelLabel(agent.model)}</span>
                    </div>
                    <div className="mt-0.5 flex items-center gap-2 text-[9px] text-muted-foreground">
                      {agent.system_prompt && <span>프롬프트 설정됨</span>}
                      {fileCount > 0 && <span className="flex items-center gap-0.5"><FileText className="h-2.5 w-2.5" />지식 {fileCount}</span>}
                    </div>
                  </div>
                  <div className="mt-auto flex items-center gap-1 pt-2">
                    <Button variant="outline" size="sm" className="h-6 flex-1 text-[10px]" onClick={() => openEdit(agent)}>
                      <Pencil className="mr-1 h-3 w-3" />설정
                    </Button>
                    <Button variant="outline" size="sm" className="h-6 w-6 p-0 text-destructive hover:bg-destructive/10" onClick={() => handleDelete(agent.id)}>
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      <Dialog open={modalOpen} onOpenChange={setModalOpen}>
        <DialogContent className="max-w-xl max-h-[80vh] overflow-y-auto">
          <DialogHeader><DialogTitle className="text-sm">{editing ? "에이전트 설정" : "에이전트 추가"}</DialogTitle></DialogHeader>
          <Tabs defaultValue="basic" className="mt-2">
            <TabsList className="h-8 w-full">
              <TabsTrigger value="basic" className="gap-1 text-xs"><Bot className="h-3 w-3" />기본</TabsTrigger>
              <TabsTrigger value="prompt" className="gap-1 text-xs"><FileText className="h-3 w-3" />프롬프트 & 지식</TabsTrigger>
              <TabsTrigger value="params" className="gap-1 text-xs"><Settings2 className="h-3 w-3" />파라미터</TabsTrigger>
            </TabsList>

            <TabsContent value="basic" className="space-y-3 pt-3">
              <div>
                <Label className="text-[11px]">이름</Label>
                <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="예: 설계 분석기" className="mt-1 h-8 text-xs" />
              </div>
              <div>
                <Label className="text-[11px]">설명</Label>
                <Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="간단한 설명" className="mt-1 h-8 text-xs" />
              </div>
              <div>
                <Label className="text-[11px]">모델</Label>
                <Select value={form.model} onValueChange={(v) => setForm({ ...form, model: v })}>
                  <SelectTrigger className="mt-1 h-8 text-xs"><SelectValue /></SelectTrigger>
                  <SelectContent className="max-h-[280px]">
                    {MODEL_GROUPS.map((group) => (
                      <div key={group.provider}>
                        <div className="flex items-center gap-1.5 px-2 py-1 text-[10px] font-semibold text-muted-foreground">
                          <span className="h-2 w-2 rounded-full" style={{ backgroundColor: group.color }} />
                          {group.provider}
                        </div>
                        {group.models.map((m) => (
                          <SelectItem key={m.value} value={m.value} className="text-xs">{m.label}</SelectItem>
                        ))}
                      </div>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </TabsContent>

            <TabsContent value="prompt" className="space-y-4 pt-3">
              <div>
                <Label className="text-[11px]">시스템 프롬프트</Label>
                <Textarea value={form.system_prompt} onChange={(e) => setForm({ ...form, system_prompt: e.target.value })}
                  placeholder="에이전트의 전문 분야, 행동 방식, 응답 규칙을 정의하세요..."
                  rows={6} className="mt-1 text-xs" />
                <p className="mt-1 text-[10px] text-muted-foreground">데이터 연결(DB, API 등)은 워크스페이스에서 설정합니다.</p>
              </div>

              <div>
                <Label className="text-[11px]">적용된 지식 파일 ({form.config.knowledge_files.length})</Label>
                {form.config.knowledge_files.length > 0 ? (
                  <div className="mt-1.5 space-y-1">
                    {form.config.knowledge_files.map((f: any, i) => (
                      <div key={i} className="flex items-center justify-between rounded-md border bg-card px-2.5 py-1.5">
                        <div className="flex items-center gap-1.5">
                          <FileText className="h-3.5 w-3.5 text-muted-foreground" />
                          <span className="text-xs font-medium">{f.name}</span>
                          <span className="text-[10px] text-muted-foreground">{(f.content.length / 1024).toFixed(1)}KB</span>
                          {f.source === "library" && <Badge variant="secondary" className="h-4 text-[8px]">라이브러리</Badge>}
                        </div>
                        <button onClick={() => removeFile(i)} className="text-destructive hover:text-destructive/80"><X className="h-3 w-3" /></button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="mt-1 text-[10px] text-muted-foreground">아래에서 라이브러리를 선택하거나 파일을 직접 업로드하세요.</p>
                )}
              </div>

              <div className="rounded-lg border p-3">
                <div className="mb-2 flex items-center justify-between">
                  <Label className="text-[11px]">지식 라이브러리에서 선택</Label>
                  {libraryLoading && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />}
                </div>
                {libraryFiles.length === 0 ? (
                  <p className="py-3 text-center text-[10px] text-muted-foreground">라이브러리에 등록된 파일이 없습니다. 관리자가 업무별 MD 파일을 라이브러리에 등록하면 여기에 표시됩니다.</p>
                ) : (
                  <div className="max-h-40 space-y-0.5 overflow-auto">
                    {(() => {
                      const categories = new Map<string, any[]>();
                      libraryFiles.forEach((f: any) => {
                        if (!categories.has(f.category)) categories.set(f.category, []);
                        categories.get(f.category)!.push(f);
                      });
                      return [...categories.entries()].map(([cat, files]) => (
                        <div key={cat}>
                          <p className="px-1 py-1 text-[9px] font-semibold uppercase tracking-wider text-muted-foreground">{cat}</p>
                          {files.map((f: any) => {
                            const alreadyAdded = form.config.knowledge_files.some((kf: any) => kf.library_id === f.id || kf.name === f.name);
                            return (
                              <button
                                key={f.id}
                                disabled={alreadyAdded}
                                className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition-colors ${alreadyAdded ? "opacity-40" : "hover:bg-accent"}`}
                                onClick={() => addLibraryFile(f)}
                              >
                                <FileText className="h-3 w-3 text-muted-foreground" />
                                <span className="flex-1 font-medium">{f.name}</span>
                                <span className="text-[10px] text-muted-foreground">{f.file_name}</span>
                                {alreadyAdded && <Badge variant="secondary" className="h-4 text-[8px]">적용됨</Badge>}
                              </button>
                            );
                          })}
                        </div>
                      ));
                    })()}
                  </div>
                )}
              </div>

              <div className="rounded-lg border border-dashed p-3">
                <Label className="text-[11px]">직접 업로드</Label>
                <p className="text-[10px] text-muted-foreground mb-2">MD, TXT, CSV 파일을 직접 업로드합니다.</p>
                <input ref={fileInputRef} type="file" accept=".md,.txt,.csv" multiple className="hidden" onChange={handleFileUpload} />
                <Button variant="outline" size="sm" className="h-7 gap-1 text-xs" onClick={() => fileInputRef.current?.click()}>
                  <Upload className="h-3 w-3" />파일 선택
                </Button>
              </div>
            </TabsContent>

            <TabsContent value="params" className="space-y-3 pt-3">
              <div>
                <Label className="text-[11px]">Temperature (창의성)</Label>
                <div className="mt-1 flex items-center gap-3">
                  <input type="range" min={0} max={1} step={0.1} value={form.config.temperature}
                    onChange={(e) => setForm({ ...form, config: { ...form.config, temperature: parseFloat(e.target.value) } })}
                    className="flex-1" />
                  <span className="w-10 text-right font-mono text-xs">{form.config.temperature}</span>
                </div>
                <p className="text-[10px] text-muted-foreground mt-1">0 = 정확하고 일관된 응답, 1 = 창의적이고 다양한 응답</p>
              </div>
              <div>
                <Label className="text-[11px]">Max Tokens</Label>
                <Input type="number" value={form.config.max_tokens}
                  onChange={(e) => setForm({ ...form, config: { ...form.config, max_tokens: parseInt(e.target.value) || 4096 } })}
                  className="mt-1 h-8 w-32 text-xs" />
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex justify-end gap-2 mt-3 pt-3 border-t">
            <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setModalOpen(false)}>취소</Button>
            <Button size="sm" className="h-7 text-xs" onClick={handleSave} disabled={saving}>
              {saving && <Loader2 className="mr-1 h-3 w-3 animate-spin" />}{editing ? "저장" : "생성"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
