"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Key, Eye, EyeOff, CheckCircle2, XCircle,
  Loader2, Save, TestTube2, Trash2,
  Shield, Info, RefreshCw, ToggleLeft, ToggleRight,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/utils";

interface GlobalKey {
  id: string;
  key_name: string;
  provider: string;
  is_active: boolean;
  description: string | null;
  masked_value: string;
  last_used_at: string | null;
  updated_at: string;
}

interface TestResult {
  key_name: string;
  success: boolean;
  info?: string;
  error?: string;
}

const PREDEFINED_KEYS = [
  { key_name: "OPENAI_API_KEY",    provider: "openai",    label: "OpenAI API Key",    placeholder: "sk-proj-xxxxxxxx",  accent: "#10a37f" },
  { key_name: "ANTHROPIC_API_KEY", provider: "anthropic", label: "Anthropic API Key", placeholder: "sk-ant-xxxxxxxx",   accent: "#cc785c" },
  { key_name: "GOOGLE_AI_API_KEY", provider: "google",    label: "Google AI API Key", placeholder: "AIzaSyxxxxxxxx",    accent: "#4285f4" },
];

// ─── Single Key Row ───────────────────────────────────────────────────────────
function KeyRow({
  keyDef, existing, testResult, onSave, onDelete, onTest, onToggle,
}: {
  keyDef: typeof PREDEFINED_KEYS[number];
  existing: GlobalKey | undefined;
  testResult: TestResult | undefined;
  onSave: (key_name: string, provider: string, value: string) => Promise<void>;
  onDelete: (key_name: string) => Promise<void>;
  onTest: (key_name: string) => Promise<void>;
  onToggle: (key_name: string, is_active: boolean) => Promise<void>;
}) {
  const [value, setValue] = useState("");
  const [show, setShow] = useState(false);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const isSet = !!existing?.masked_value && !existing.masked_value.includes("[");
  const isActive = existing?.is_active ?? false;

  return (
    <div
      className="rounded-2xl p-5 transition-all"
      style={{
        background: isSet
          ? `linear-gradient(135deg, ${keyDef.accent}10, ${keyDef.accent}04)`
          : "rgba(255,255,255,0.02)",
        border: isSet
          ? `1px solid ${keyDef.accent}28`
          : "1px dashed rgba(212,175,55,0.15)",
      }}
    >
      {/* Header */}
      <div className="flex items-start justify-between gap-3 mb-4">
        <div className="flex items-center gap-2.5">
          {/* Provider dot */}
          <div className="w-2.5 h-2.5 rounded-full flex-shrink-0"
            style={{ background: keyDef.accent, boxShadow: `0 0 6px ${keyDef.accent}80` }} />
          <span className="font-semibold text-sm">{keyDef.label}</span>
          <span className="text-xs text-muted-foreground">({keyDef.provider})</span>

          {/* Active toggle */}
          {isSet && (
            <button onClick={() => onToggle(keyDef.key_name, !isActive)} title={isActive ? "Nonaktifkan" : "Aktifkan"}>
              {isActive
                ? <ToggleRight className="w-5 h-5 text-emerald-400" />
                : <ToggleLeft className="w-5 h-5 text-muted-foreground" />}
            </button>
          )}
        </div>

        {/* Test result */}
        {testResult && (
          <span className={cn(
            "flex items-center gap-1 text-xs px-2.5 py-1 rounded-full font-medium",
            testResult.success
              ? "bg-emerald-500/15 text-emerald-400"
              : "bg-red-500/15 text-red-400"
          )}>
            {testResult.success
              ? <><CheckCircle2 className="w-3 h-3" />{testResult.info}</>
              : <><XCircle className="w-3 h-3" />{testResult.error}</>}
          </span>
        )}
      </div>

      {/* Masked current value */}
      {isSet && (
        <div className="flex items-center gap-2 mb-4 text-xs text-muted-foreground p-2.5 rounded-lg"
          style={{ background: "rgba(212,175,55,0.05)", border: "1px solid rgba(212,175,55,0.1)" }}>
          <Key className="w-3.5 h-3.5 text-amber-400/60 flex-shrink-0" />
          <code className="font-mono flex-1">{existing!.masked_value}</code>
          {existing!.last_used_at && (
            <span className="text-xs opacity-60">Dipakai: {formatDate(existing!.last_used_at)}</span>
          )}
        </div>
      )}

      {/* Input */}
      <div className="flex gap-2">
        <div className="relative flex-1">
          <input
            type={show ? "text" : "password"}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            placeholder={isSet ? "Masukkan key baru untuk update..." : keyDef.placeholder}
            className="w-full pr-9 pl-3 py-2.5 rounded-xl bg-card focus:outline-none text-sm font-mono transition-all"
            style={{ border: "1px solid rgba(212,175,55,0.15)" }}
            onFocus={(e) => { e.currentTarget.style.border = "1px solid rgba(212,175,55,0.4)"; }}
            onBlur={(e) => { e.currentTarget.style.border = "1px solid rgba(212,175,55,0.15)"; }}
          />
          <button
            type="button"
            onClick={() => setShow(!show)}
            className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
          >
            {show ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
          </button>
        </div>

        {/* Save */}
        <button
          onClick={async () => {
            if (!value.trim()) return;
            setSaving(true);
            try { await onSave(keyDef.key_name, keyDef.provider, value); setValue(""); }
            finally { setSaving(false); }
          }}
          disabled={saving || !value.trim()}
          className="flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-medium transition-all disabled:opacity-50"
          style={{
            background: `linear-gradient(135deg, ${keyDef.accent}cc, ${keyDef.accent}99)`,
            color: "#fff",
            boxShadow: saving ? "none" : `0 2px 12px ${keyDef.accent}40`,
          }}
        >
          {saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Save className="w-3.5 h-3.5" />}
          {isSet ? "Update" : "Simpan"}
        </button>

        {/* Test */}
        {isSet && (
          <button
            onClick={async () => { setTesting(true); try { await onTest(keyDef.key_name); } finally { setTesting(false); } }}
            disabled={testing}
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-sm transition-all hover:bg-white/5 disabled:opacity-50"
            style={{ border: "1px solid rgba(212,175,55,0.2)" }}
          >
            {testing ? <Loader2 className="w-3.5 h-3.5 animate-spin text-amber-400" /> : <TestTube2 className="w-3.5 h-3.5" />}
            Test
          </button>
        )}

        {/* Delete */}
        {isSet && (
          <button
            onClick={async () => {
              if (!confirm(`Hapus ${keyDef.key_name}?`)) return;
              setDeleting(true);
              try { await onDelete(keyDef.key_name); } finally { setDeleting(false); }
            }}
            disabled={deleting}
            className="w-9 h-9 rounded-xl flex items-center justify-center text-muted-foreground hover:text-red-400 hover:bg-red-500/10 disabled:opacity-50 transition-all"
            style={{ border: "1px solid rgba(212,175,55,0.15)" }}
          >
            {deleting ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
          </button>
        )}
      </div>
    </div>
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────
export default function AdminSettingsPage() {
  const [keys, setKeys] = useState<GlobalKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [testResults, setTestResults] = useState<Record<string, TestResult>>({});

  const fetchKeys = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/api-keys");
      const data = await res.json();
      setKeys(data.data ?? []);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleSave(key_name: string, provider: string, value: string) {
    const res = await fetch("/api/admin/api-keys", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ key_name, value, provider }),
    });
    const data = await res.json();
    if (!res.ok) { toast.error(data.error ?? "Gagal menyimpan key"); return; }
    toast.success(`${key_name} berhasil disimpan!`);
    await fetchKeys();
    setTestResults((prev) => { const n = { ...prev }; delete n[key_name]; return n; });
  }

  async function handleDelete(key_name: string) {
    const res = await fetch(`/api/admin/api-keys?key_name=${key_name}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) { toast.error(data.error ?? "Gagal hapus key"); return; }
    toast.success(`${key_name} dihapus`);
    await fetchKeys();
  }

  async function handleTest(key_name: string) {
    const res = await fetch(`/api/admin/api-keys?test=${key_name}`);
    const data = await res.json();
    setTestResults((prev) => ({ ...prev, [key_name]: { key_name, ...data } }));
    if (data.success) toast.success(`${key_name}: ${data.info}`);
    else toast.error(`${key_name}: ${data.error}`);
  }

  async function handleToggle(key_name: string, is_active: boolean) {
    const res = await fetch("/api/admin/api-keys", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ key_name, is_active }),
    });
    const data = await res.json();
    if (!res.ok) { toast.error(data.error ?? "Gagal update"); return; }
    toast.success(`${key_name} ${is_active ? "diaktifkan" : "dinonaktifkan"}`);
    await fetchKeys();
  }

  const getExisting = (key_name: string) => keys.find((k) => k.key_name === key_name);
  const activeKeys = keys.filter((k) => k.is_active).length;

  return (
    <div className="max-w-3xl mx-auto space-y-6">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">API Keys Global</h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            Keys ini digunakan semua user sebagai fallback otomatis
          </p>
        </div>
        <button onClick={fetchKeys} disabled={loading}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-all hover:bg-white/5 disabled:opacity-50"
          style={{ border: "1px solid rgba(212,175,55,0.2)" }}>
          <RefreshCw className={cn("w-3.5 h-3.5", loading && "animate-spin")} />
          Refresh
        </button>
      </div>

      {/* Info banner */}
      <div className="rounded-2xl p-4 flex items-start gap-3 text-sm"
        style={{ background: "rgba(59,130,246,0.08)", border: "1px solid rgba(59,130,246,0.2)" }}>
        <Info className="w-5 h-5 flex-shrink-0 mt-0.5 text-blue-400" />
        <div className="text-blue-200">
          <p className="font-medium">Cascade Priority</p>
          <p className="text-xs mt-1 opacity-80">
            User Key → User Settings → <strong>Global Key (ini)</strong> → ENV File
            <br />User tidak dapat melihat atau mengubah keys ini.
          </p>
        </div>
      </div>

      {/* Status */}
      {!loading && (
        <div className="rounded-xl p-3 flex items-center gap-3 text-sm"
          style={{
            background: activeKeys > 0 ? "rgba(212,175,55,0.06)" : "rgba(239,68,68,0.08)",
            border: activeKeys > 0 ? "1px solid rgba(212,175,55,0.2)" : "1px solid rgba(239,68,68,0.2)",
          }}>
          <div className={cn("w-2.5 h-2.5 rounded-full flex-shrink-0",
            activeKeys > 0 ? "bg-amber-400 animate-pulse" : "bg-red-500")} />
          {activeKeys > 0
            ? <><span style={{ color: "#d4af37" }} className="font-medium">{activeKeys} key aktif</span>
              <span className="text-muted-foreground"> — semua user dapat menggunakan AI</span></>
            : <><span className="text-red-400 font-medium">Tidak ada key aktif</span>
              <span className="text-muted-foreground"> — user harus set key sendiri</span></>}
        </div>
      )}

      {/* Gold divider */}
      <div className="gold-hr" />

      {/* Keys */}
      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-6 h-6 animate-spin text-amber-400/50" />
        </div>
      ) : (
        <div className="space-y-3">
          {PREDEFINED_KEYS.map((keyDef) => (
            <KeyRow
              key={keyDef.key_name}
              keyDef={keyDef}
              existing={getExisting(keyDef.key_name)}
              testResult={testResults[keyDef.key_name]}
              onSave={handleSave}
              onDelete={handleDelete}
              onTest={handleTest}
              onToggle={handleToggle}
            />
          ))}
        </div>
      )}

      {/* Security note */}
      <div className="rounded-xl p-4 flex items-start gap-3 text-xs"
        style={{ background: "rgba(212,175,55,0.04)", border: "1px solid rgba(212,175,55,0.12)" }}>
        <Shield className="w-4 h-4 flex-shrink-0 mt-0.5 text-amber-400/70" />
        <p className="text-muted-foreground">
          Keys dienkripsi <strong>AES-256-GCM</strong> sebelum disimpan.
          Nilai asli tidak pernah dikirim ke browser — hanya versi tersensor yang ditampilkan.
          Dekripsi hanya terjadi di server.
        </p>
      </div>
    </div>
  );
}
