"use client";

import { useEffect, useState, useCallback } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Plus, Pencil, Trash2, Loader2, CheckCircle2, XCircle, Eye, EyeOff } from "lucide-react";
import { toast } from "sonner";

const PROVIDER_CONFIG: Record<string, {
  label: string;
  color: string;
  icon: string;
  endpoint: string;
  keyPlaceholder: string;
  keyPrefix: string;
  models: { value: string; label: string }[];
}> = {
  anthropic: {
    label: "Anthropic",
    color: "#D97757",
    icon: "A",
    endpoint: "https://api.anthropic.com",
    keyPlaceholder: "sk-ant-api03-...",
    keyPrefix: "sk-ant-",
    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" },
    ],
  },
  openai: {
    label: "OpenAI",
    color: "#10A37F",
    icon: "G",
    endpoint: "https://api.openai.com",
    keyPlaceholder: "sk-proj-...",
    keyPrefix: "sk-",
    models: [
      { value: "gpt-4o", label: "GPT-4o" },
      { value: "gpt-4o-mini", label: "GPT-4o Mini" },
      { value: "gpt-4-turbo", label: "GPT-4 Turbo" },
      { value: "o1", label: "o1" },
      { value: "o1-mini", label: "o1 Mini" },
      { value: "o3-mini", label: "o3 Mini" },
    ],
  },
  google: {
    label: "Google",
    color: "#4285F4",
    icon: "G",
    endpoint: "https://generativelanguage.googleapis.com/v1beta/openai",
    keyPlaceholder: "AIza...",
    keyPrefix: "AIza",
    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" },
    ],
  },
  deepseek: {
    label: "DeepSeek",
    color: "#0066FF",
    icon: "D",
    endpoint: "https://api.deepseek.com",
    keyPlaceholder: "sk-...",
    keyPrefix: "sk-",
    models: [
      { value: "deepseek-chat", label: "DeepSeek Chat (V3)" },
      { value: "deepseek-reasoner", label: "DeepSeek Reasoner (R1)" },
    ],
  },
  ollama: {
    label: "Ollama (로컬)",
    color: "#1D1D1D",
    icon: "O",
    endpoint: "http://localhost:11434",
    keyPlaceholder: "필요 없음",
    keyPrefix: "",
    models: [
      { value: "llama3.1", label: "Llama 3.1" },
      { value: "llama3.2", label: "Llama 3.2" },
      { value: "mistral", label: "Mistral" },
      { value: "codellama", label: "Code Llama" },
      { value: "qwen2.5", label: "Qwen 2.5" },
    ],
  },
};

const PROVIDER_LIST = Object.entries(PROVIDER_CONFIG).map(([key, cfg]) => ({
  value: key,
  ...cfg,
}));

export default function ProviderListPage() {
  const [providers, setProviders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [showKey, setShowKey] = useState(false);
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({
    name: "anthropic",
    display_name: "",
    api_key: "",
    model_name: "",
    endpoint: "",
    max_tokens: 4096,
    temperature: 0.7,
    cost_per_1k_input: 0,
    cost_per_1k_output: 0,
  });

  const selectedConfig = PROVIDER_CONFIG[form.name] || PROVIDER_CONFIG.anthropic;

  const loadProviders = useCallback(async () => {
    setLoading(true);
    try {
      const res = await aiAgentApi.listProviders();
      setProviders(res.data || []);
    } catch {
      toast.error("프로바이더 목록 로드 실패");
    }
    setLoading(false);
  }, []);

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

  const openCreate = (providerName?: string) => {
    setEditing(null);
    setShowKey(false);
    const cfg = PROVIDER_CONFIG[providerName || "anthropic"];
    setForm({
      name: providerName || "anthropic",
      display_name: cfg.label,
      api_key: "",
      model_name: "",
      endpoint: cfg.endpoint,
      max_tokens: 4096,
      temperature: 0.7,
      cost_per_1k_input: 0,
      cost_per_1k_output: 0,
    });
    setModalOpen(true);
  };

  const openEdit = (p: any) => {
    setEditing(p);
    setShowKey(false);
    setForm({
      name: p.name,
      display_name: p.display_name,
      api_key: "",
      model_name: p.model_name,
      endpoint: p.endpoint || PROVIDER_CONFIG[p.name]?.endpoint || "",
      max_tokens: p.max_tokens,
      temperature: parseFloat(p.temperature),
      cost_per_1k_input: parseFloat(p.cost_per_1k_input || 0),
      cost_per_1k_output: parseFloat(p.cost_per_1k_output || 0),
    });
    setModalOpen(true);
  };

  const handleProviderChange = (name: string) => {
    const cfg = PROVIDER_CONFIG[name];
    if (!cfg) return;
    setForm((prev) => ({
      ...prev,
      name,
      display_name: editing ? prev.display_name : cfg.label,
      model_name: "",
      endpoint: cfg.endpoint,
    }));
  };

  const handleSave = async () => {
    if (!form.display_name) { toast.error("표시 이름을 입력하세요."); return; }
    if (!editing && !form.api_key && form.name !== "ollama") { toast.error("API 키를 입력하세요."); return; }

    setSaving(true);
    try {
      const data = { ...form };
      if (editing && !data.api_key) delete (data as any).api_key;
      if (form.name === "ollama" && !data.api_key) data.api_key = "ollama";

      if (editing) {
        await aiAgentApi.updateProvider(editing.id, data);
        toast.success("프로바이더가 수정되었습니다.");
      } else {
        await aiAgentApi.createProvider(data);
        toast.success("프로바이더가 추가되었습니다.");
      }
      setModalOpen(false);
      loadProviders();
    } catch (e: any) {
      toast.error(e.response?.data?.message || "저장 실패");
    }
    setSaving(false);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("프로바이더를 삭제하시겠습니까?")) return;
    try { await aiAgentApi.deleteProvider(id); toast.success("삭제 완료"); loadProviders(); }
    catch { toast.error("삭제 실패"); }
  };

  const handleToggle = async (id: number, active: boolean) => {
    try { await aiAgentApi.updateProvider(id, { is_active: active }); loadProviders(); }
    catch { toast.error("상태 변경 실패"); }
  };

  return (
    <div className="flex h-full flex-col bg-background">
      <div className="shrink-0 space-y-4 p-6 pb-4">
        <div>
          <h1 className="text-xl font-bold">LLM 프로바이더 관리</h1>
          <p className="text-sm text-muted-foreground">AI 모델 API 키를 등록하고 에이전트에서 사용할 수 있도록 설정합니다</p>
        </div>
      </div>

      <div className="flex-1 overflow-auto px-6 pb-6">
        <div className="mb-6">
          <p className="text-xs font-semibold text-muted-foreground mb-3 uppercase tracking-wider">프로바이더 추가</p>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
            {PROVIDER_LIST.map((p) => (
              <button
                key={p.value}
                onClick={() => openCreate(p.value)}
                className="flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-border/60 p-4 transition-all hover:border-primary/40 hover:bg-accent/30 group"
              >
                <div
                  className="flex h-10 w-10 items-center justify-center rounded-xl text-white text-sm font-bold transition-transform group-hover:scale-110"
                  style={{ backgroundColor: p.color }}
                >
                  {p.icon}
                </div>
                <div className="text-center">
                  <p className="text-xs font-semibold">{p.label}</p>
                  <p className="text-[10px] text-muted-foreground">{p.models.length}개 모델</p>
                </div>
                <Plus className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
              </button>
            ))}
          </div>
        </div>

        <div>
          <p className="text-xs font-semibold text-muted-foreground mb-3 uppercase tracking-wider">
            등록된 프로바이더 ({providers.length})
          </p>

          {loading ? (
            <div className="flex items-center justify-center py-12"><Loader2 className="h-6 w-6 animate-spin" /></div>
          ) : providers.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-muted-foreground rounded-xl border border-dashed">
              <p className="text-sm">등록된 프로바이더가 없습니다</p>
              <p className="text-xs mt-1">위에서 프로바이더를 선택하여 API 키를 등록하세요</p>
            </div>
          ) : (
            <div className="space-y-2">
              {providers.map((p) => {
                const cfg = PROVIDER_CONFIG[p.name];
                return (
                  <div key={p.id} className="flex items-center justify-between rounded-xl border bg-card p-4 transition-colors hover:bg-accent/20">
                    <div className="flex items-center gap-4">
                      <div
                        className="flex h-10 w-10 items-center justify-center rounded-xl text-white text-sm font-bold"
                        style={{ backgroundColor: cfg?.color || "#666" }}
                      >
                        {cfg?.icon || "?"}
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <p className="text-sm font-semibold">{p.display_name}</p>
                          {p.is_active ? (
                            <span className="flex items-center gap-0.5 text-[10px] text-green-600"><CheckCircle2 className="h-3 w-3" />활성</span>
                          ) : (
                            <span className="flex items-center gap-0.5 text-[10px] text-gray-400"><XCircle className="h-3 w-3" />비활성</span>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground">
                          {cfg?.label || p.name}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-xs text-muted-foreground font-mono bg-muted rounded px-2 py-0.5">{p.api_key_masked}</span>
                      <Switch checked={p.is_active} onCheckedChange={(v) => handleToggle(p.id, v)} />
                      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => openEdit(p)}>
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      <Button variant="ghost" size="icon" className="h-8 w-8 text-destructive" onClick={() => handleDelete(p.id)}>
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      <Dialog open={modalOpen} onOpenChange={setModalOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <div
                className="flex h-7 w-7 items-center justify-center rounded-lg text-white text-xs font-bold"
                style={{ backgroundColor: selectedConfig.color }}
              >
                {selectedConfig.icon}
              </div>
              {editing ? "프로바이더 수정" : "프로바이더 추가"}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 pt-2">
            <div>
              <Label className="text-xs">프로바이더</Label>
              <Select value={form.name} onValueChange={handleProviderChange} disabled={!!editing}>
                <SelectTrigger className="mt-1">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {PROVIDER_LIST.map((p) => (
                    <SelectItem key={p.value} value={p.value}>
                      <div className="flex items-center gap-2">
                        <div className="h-3 w-3 rounded" style={{ backgroundColor: p.color }} />
                        {p.label}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label className="text-xs">표시 이름</Label>
              <Input value={form.display_name} onChange={(e) => setForm({ ...form, display_name: e.target.value })} placeholder="내 Claude 키" className="mt-1" />
            </div>

            <div>
              <Label className="text-xs">
                API 키 {editing && <span className="text-muted-foreground">(비우면 기존 키 유지)</span>}
              </Label>
              <div className="relative mt-1">
                <Input
                  type={showKey ? "text" : "password"}
                  value={form.api_key}
                  onChange={(e) => setForm({ ...form, api_key: e.target.value })}
                  placeholder={selectedConfig.keyPlaceholder}
                  className="pr-10 font-mono text-sm"
                  disabled={form.name === "ollama"}
                />
                <button
                  type="button"
                  onClick={() => setShowKey(!showKey)}
                  className="absolute top-1/2 right-3 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-2">
              <Button variant="outline" onClick={() => setModalOpen(false)}>취소</Button>
              <Button onClick={handleSave} disabled={saving}>
                {saving && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
                {editing ? "수정" : "추가"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
