"use client";

import { useEffect, useState, useCallback } from "react";
import {
  CheckCircle2, AlertCircle,
  Loader2, Save, Sliders, Bell, User, Info,
  Key, Eye, EyeOff, ExternalLink, Trash2, RefreshCw,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { ENV_VAR_META } from "@/types/env-vars";

interface PrefsData {
  preferred_ai_provider: string;
  preferred_model: string | null;
  default_language: string;
  default_mode: string;
  default_variations: number;
  email_notifications: boolean;
}

// ─── Section Card ─────────────────────────────────────────────────────────────
function SectionCard({
  icon, title, description, children, accent = "#d4af37",
}: {
  icon: React.ReactNode;
  title: string;
  description: string;
  children: React.ReactNode;
  accent?: string;
}) {
  return (
    <div className="rounded-2xl p-6 space-y-5"
      style={{ background: "rgba(255,255,255,0.025)", border: "1px solid rgba(212,175,55,0.14)" }}>
      <div className="flex items-start gap-3.5 pb-1">
        <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
          style={{ background: `${accent}18`, border: `1px solid ${accent}30` }}>
          <span style={{ color: accent }}>{icon}</span>
        </div>
        <div>
          <h2 className="font-semibold text-base">{title}</h2>
          <p className="text-xs text-muted-foreground mt-0.5">{description}</p>
        </div>
      </div>

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

      <div className="space-y-4">{children}</div>
    </div>
  );
}

// ─── Toggle ───────────────────────────────────────────────────────────────────
function Toggle({ checked, onChange }: { checked: boolean; onChange: () => void }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={onChange}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onChange(); } }}
      className="relative w-11 h-6 rounded-full transition-all cursor-pointer flex-shrink-0 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-400 focus-visible:ring-offset-2 focus-visible:ring-offset-background"
      style={{
        background: checked
          ? "linear-gradient(90deg, #d4af37, #b8860b)"
          : "rgba(255,255,255,0.08)",
        border: checked ? "1px solid rgba(212,175,55,0.5)" : "1px solid rgba(255,255,255,0.12)",
        boxShadow: checked ? "0 0 10px rgba(212,175,55,0.25)" : "none",
      }}
    >
      <div className={cn(
        "absolute top-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform",
        checked ? "translate-x-5" : "translate-x-0.5"
      )} />
    </button>
  );
}

// ─── Select ───────────────────────────────────────────────────────────────────
function GoldSelect({
  value, onChange, children,
}: {
  value: string | number;
  onChange: (v: string) => void;
  children: React.ReactNode;
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="w-full px-3 py-2.5 rounded-xl bg-card focus:outline-none text-sm transition-all appearance-none"
      style={{ border: "1px solid rgba(212,175,55,0.15)" }}
      onFocus={(e) => { e.currentTarget.style.border = "1px solid rgba(212,175,55,0.45)"; }}
      onBlur={(e) => { e.currentTarget.style.border = "1px solid rgba(212,175,55,0.15)"; }}
    >
      {children}
    </select>
  );
}

// ─── Save Button ──────────────────────────────────────────────────────────────
function SaveBtn({ loading, onClick }: { loading: boolean; onClick: () => void }) {
  return (
    <button
      onClick={onClick}
      disabled={loading}
      className="flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-all disabled:opacity-60"
      style={{
        background: "linear-gradient(135deg, rgba(212,175,55,0.8), rgba(180,134,11,0.8))",
        boxShadow: loading ? "none" : "0 2px 16px rgba(212,175,55,0.25)",
        color: "#1a1200",
      }}
    >
      {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
      {loading ? "Menyimpan..." : "Simpan"}
    </button>
  );
}

// ─── API Key Input Row ────────────────────────────────────────────────────────
function ApiKeyRow({
  meta,
  savedMasked,
  onSave,
  onDelete,
  saving,
  deleting,
}: {
  meta: typeof ENV_VAR_META[number];
  savedMasked: string | null;
  onSave: (key: string, value: string) => Promise<void>;
  onDelete: (key: string) => Promise<void>;
  saving: boolean;
  deleting: boolean;
}) {
  const [value, setValue]     = useState("");
  const [visible, setVisible] = useState(false);

  const handleSave = async () => {
    if (!value.trim()) { toast.error("Value tidak boleh kosong"); return; }
    await onSave(meta.key, value.trim());
    setValue("");
  };

  return (
    <div className="rounded-xl p-3.5 space-y-2"
      style={{ background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)" }}>
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-sm font-medium">{meta.label}</span>
            {savedMasked && (
              <span className="text-[10px] px-2 py-0.5 rounded-full font-mono"
                style={{ background: "rgba(34,197,94,0.1)", color: "#4ade80", border: "1px solid rgba(34,197,94,0.2)" }}>
                ✓ {savedMasked}
              </span>
            )}
          </div>
          <p className="text-xs text-muted-foreground mt-0.5">{meta.description}</p>
        </div>
        {meta.docUrl && (
          <a href={meta.docUrl} target="_blank" rel="noopener noreferrer"
            className="flex-shrink-0 text-muted-foreground hover:text-foreground transition-colors mt-0.5">
            <ExternalLink className="w-3.5 h-3.5" />
          </a>
        )}
      </div>

      <div className="flex gap-2">
        <div className="relative flex-1">
          <input
            type={visible ? "text" : "password"}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            placeholder={savedMasked ? `Update: ${meta.placeholder}` : meta.placeholder}
            className="w-full px-3 py-2 pr-9 rounded-lg bg-card text-sm focus:outline-none transition-all font-mono"
            style={{ border: "1px solid rgba(212,175,55,0.12)" }}
            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.12)"; }}
            onKeyDown={(e) => { if (e.key === "Enter") handleSave(); }}
          />
          {meta.isSecret && (
            <button type="button" onClick={() => setVisible(!visible)}
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground">
              {visible ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
            </button>
          )}
        </div>
        <button
          type="button" onClick={handleSave} disabled={saving || !value.trim()}
          className="px-3 py-2 rounded-lg text-xs font-medium flex items-center gap-1.5 disabled:opacity-40 transition-all flex-shrink-0"
          style={{ background: "rgba(212,175,55,0.15)", color: "#d4af37", border: "1px solid rgba(212,175,55,0.3)" }}
        >
          {saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Save className="w-3.5 h-3.5" />}
          Simpan
        </button>
        {savedMasked && (
          <button
            type="button" onClick={() => onDelete(meta.key)} disabled={deleting}
            className="px-2.5 py-2 rounded-lg text-xs flex items-center gap-1 disabled:opacity-40 transition-all flex-shrink-0"
            style={{ background: "rgba(239,68,68,0.08)", color: "#f87171", border: "1px solid rgba(239,68,68,0.2)" }}
          >
            {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 SettingsPage() {
  const supabase = createClient();

  const [prefs, setPrefs] = useState<PrefsData>({
    preferred_ai_provider: "auto",
    preferred_model: "",
    default_language: "id",
    default_mode: "simple",
    default_variations: 1,
    email_notifications: true,
  });
  const [loadingPrefs, setLoadingPrefs] = useState(true);
  const [savingPrefs, setSavingPrefs] = useState(false);

  const [profileName, setProfileName] = useState("");
  const [savingProfile, setSavingProfile] = useState(false);

  const [aiKeyStatus, setAiKeyStatus] = useState<{
    has_key: boolean;
    provider: string;
  } | null>(null);

  // ── API Keys state ─────────────────────────────────────────────────────────
  const [savedKeys, setSavedKeys]     = useState<Record<string, string>>({}); // key → masked
  const [loadingKeys, setLoadingKeys] = useState(false);
  const [savingKey, setSavingKey]     = useState<string | null>(null);
  const [deletingKey, setDeletingKey] = useState<string | null>(null);

  const fetchApiKeys = useCallback(async () => {
    setLoadingKeys(true);
    try {
      const res = await fetch("/api/env-vars");
      if (!res.ok) return;
      const { data } = await res.json() as { data: Array<{ key: string; masked_value: string }> };
      const map: Record<string, string> = {};
      for (const item of data ?? []) map[item.key] = item.masked_value;
      setSavedKeys(map);
    } finally {
      setLoadingKeys(false);
    }
  }, []);

  const handleSaveKey = async (key: string, value: string) => {
    setSavingKey(key);
    try {
      const res = await fetch("/api/env-vars", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ vars: [{ key, value, category: "ai_provider" }] }),
      });
      const data = await res.json();
      if (data.success) {
        toast.success(`${key} berhasil disimpan!`);
        await fetchApiKeys();
        await fetchPrefs();
      } else {
        toast.error(data.results?.[0]?.error ?? "Gagal menyimpan key");
      }
    } finally {
      setSavingKey(null);
    }
  };

  const handleDeleteKey = async (key: string) => {
    setDeletingKey(key);
    try {
      const res = await fetch(`/api/env-vars?key=${encodeURIComponent(key)}`, { method: "DELETE" });
      const data = await res.json();
      if (data.success) {
        toast.success(`${key} dihapus`);
        await fetchApiKeys();
        await fetchPrefs();
      } else {
        toast.error("Gagal menghapus key");
      }
    } finally {
      setDeletingKey(null);
    }
  };

  const fetchPrefs = useCallback(async () => {
    setLoadingPrefs(true);
    try {
      const res = await fetch("/api/settings");
      if (!res.ok) return;
      const { data } = await res.json();
      if (!data) return;
      setPrefs({
        preferred_ai_provider: data.preferred_ai_provider ?? "auto",
        preferred_model: data.preferred_model ?? "",
        default_language: data.default_language ?? "id",
        default_mode: data.default_mode ?? "simple",
        default_variations: data.default_variations ?? 1,
        email_notifications: data.email_notifications ?? true,
      });
      setAiKeyStatus({
        has_key: data.has_openai_key || data.has_anthropic_key || data.has_google_key,
        provider: data.has_openai_key ? "OpenAI"
          : data.has_anthropic_key ? "Anthropic"
          : data.has_google_key ? "Google AI"
          : "—",
      });
    } finally {
      setLoadingPrefs(false);
    }
  }, []);

  useEffect(() => {
    fetchPrefs();
    fetchApiKeys();
    supabase.auth.getUser().then(({ data: { user } }) => {
      if (!user) return;
      supabase.from("profiles").select("full_name").eq("id", user.id).single()
        .then(({ data }) => { if (data?.full_name) setProfileName(data.full_name); });
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetchPrefs, fetchApiKeys]);

  async function handleSavePrefs() {
    setSavingPrefs(true);
    try {
      const res = await fetch("/api/settings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          preferred_ai_provider: prefs.preferred_ai_provider,
          preferred_model: prefs.preferred_model || null,
          default_language: prefs.default_language,
          default_mode: prefs.default_mode,
          default_variations: prefs.default_variations,
          email_notifications: prefs.email_notifications,
        }),
      });
      if (!res.ok) { toast.error("Gagal menyimpan"); return; }
      toast.success("Preferensi disimpan!");
    } finally {
      setSavingPrefs(false);
    }
  }

  async function handleSaveProfile() {
    if (!profileName.trim()) return;
    setSavingProfile(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;
      const { error } = await supabase
        .from("profiles").update({ full_name: profileName.trim() }).eq("id", user.id);
      if (error) { toast.error(error.message); return; }
      toast.success("Profil diperbarui!");
    } finally {
      setSavingProfile(false);
    }
  }

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

      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold">Pengaturan</h1>
        <p className="text-sm text-muted-foreground mt-1">Preferensi akun dan generate prompt</p>
      </div>

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

      {/* AI Status Banner */}
      <div className="rounded-2xl p-4 flex items-start gap-3 text-sm"
        style={{
          background: aiKeyStatus?.has_key
            ? "rgba(212,175,55,0.06)"
            : "rgba(239,68,68,0.06)",
          border: aiKeyStatus?.has_key
            ? "1px solid rgba(212,175,55,0.25)"
            : "1px solid rgba(239,68,68,0.2)",
        }}>
        {aiKeyStatus?.has_key
          ? <CheckCircle2 className="w-5 h-5 flex-shrink-0 mt-0.5 text-amber-400" />
          : <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5 text-red-400" />}
        <div>
          {aiKeyStatus?.has_key ? (
            <>
              <p className="font-medium" style={{ color: "#d4af37" }}>AI Provider Aktif</p>
              <p className="text-xs mt-0.5 text-muted-foreground">
                {aiKeyStatus.provider} tersedia — kamu bisa langsung generate prompt.
              </p>
            </>
          ) : (
            <>
              <p className="font-medium text-red-400">Belum ada AI key aktif</p>
              <p className="text-xs mt-0.5 text-muted-foreground">
                Tambahkan API key di bagian <strong className="text-foreground/70">API Keys</strong> di bawah untuk mulai generate.
              </p>
            </>
          )}
        </div>
      </div>

      {/* ── API Keys ── */}
      <SectionCard
        icon={<Key className="w-5 h-5" />}
        title="API Keys"
        description="Kelola API key AI provider kamu. Key dienkripsi AES-256 sebelum disimpan."
        accent="#f59e0b"
      >
        {/* AgentRouter highlight banner */}
        <div className="rounded-xl p-3.5 flex items-start gap-3"
          style={{ background: "rgba(245,158,11,0.06)", border: "1px solid rgba(245,158,11,0.2)" }}>
          <span className="text-xl flex-shrink-0">🌐</span>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold" style={{ color: "#f59e0b" }}>
              AgentRouter — Rekomendasi untuk Pemula
            </p>
            <p className="text-xs text-muted-foreground mt-1 leading-relaxed">
              Satu key untuk akses <strong className="text-foreground/80">30+ AI provider</strong> sekaligus
              (GPT-4o, Claude, Gemini, DeepSeek, dll). Non-profit, pay-per-use, harga lebih murah.
              Daftar gratis di{" "}
              <a href="https://agentrouter.org/console" target="_blank" rel="noopener noreferrer"
                className="underline hover:text-amber-400 transition-colors">
                agentrouter.org/console
              </a>
            </p>
          </div>
        </div>

        {loadingKeys ? (
          <div className="flex items-center justify-center py-6">
            <Loader2 className="w-5 h-5 animate-spin text-amber-400/50" />
          </div>
        ) : (
          <div className="space-y-3">
            {ENV_VAR_META.filter((m) => m.category === "ai_provider" && m.isSecret).map((meta) => (
              <ApiKeyRow
                key={meta.key}
                meta={meta}
                savedMasked={savedKeys[meta.key] ?? null}
                onSave={handleSaveKey}
                onDelete={handleDeleteKey}
                saving={savingKey === meta.key}
                deleting={deletingKey === meta.key}
              />
            ))}
          </div>
        )}

        <div className="flex items-center justify-between pt-1">
          <p className="text-[11px] text-muted-foreground flex items-center gap-1.5">
            <Info className="w-3 h-3" />
            Key dienkripsi AES-256-GCM + pgcrypto sebelum disimpan ke database
          </p>
          <button
            type="button" onClick={fetchApiKeys} disabled={loadingKeys}
            className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40"
          >
            <RefreshCw className={cn("w-3 h-3", loadingKeys && "animate-spin")} /> Refresh
          </button>
        </div>
      </SectionCard>

      {/* ── Profil ── */}
      <SectionCard
        icon={<User className="w-5 h-5" />}
        title="Profil"
        description="Perbarui nama tampilan akunmu."
        accent="#d4af37"
      >
        <div>
          <label className="text-xs text-muted-foreground mb-1.5 block font-medium">Nama Lengkap</label>
          <input
            value={profileName}
            onChange={(e) => setProfileName(e.target.value)}
            placeholder="Masukkan nama kamu"
            className="w-full px-3 py-2.5 rounded-xl bg-card focus:outline-none text-sm 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.45)"; }}
            onBlur={(e) => { e.currentTarget.style.border = "1px solid rgba(212,175,55,0.15)"; }}
          />
        </div>
        <div className="flex justify-end">
          <SaveBtn loading={savingProfile} onClick={handleSaveProfile} />
        </div>
      </SectionCard>

      {/* ── Preferensi ── */}
      <SectionCard
        icon={<Sliders className="w-5 h-5" />}
        title="Preferensi Generate"
        description="Default yang dipakai saat membuka form generator."
        accent="#8b5cf6"
      >
        {loadingPrefs ? (
          <div className="flex items-center justify-center py-6">
            <Loader2 className="w-5 h-5 animate-spin text-amber-400/50" />
          </div>
        ) : (
          <>
            <div className="grid grid-cols-2 gap-4">
              <div className="col-span-2">
                <label className="text-xs text-muted-foreground mb-1.5 block font-medium">Provider Prioritas</label>
                <GoldSelect
                  value={prefs.preferred_ai_provider}
                  onChange={(v) => setPrefs((p) => ({ ...p, preferred_ai_provider: v }))}
                >
                  <option value="auto">🤖 Auto (AgentRouter → OpenAI → Anthropic → Google)</option>
                  <option value="agentrouter">🌐 AgentRouter (30+ provider, 1 key)</option>
                  <option value="openai">OpenAI (GPT-4o / GPT-4o-mini)</option>
                  <option value="anthropic">Anthropic (Claude)</option>
                  <option value="google">Google AI (Gemini)</option>
                </GoldSelect>
              </div>
              <div>
                <label className="text-xs text-muted-foreground mb-1.5 block font-medium">Bahasa Default</label>
                <GoldSelect
                  value={prefs.default_language}
                  onChange={(v) => setPrefs((p) => ({ ...p, default_language: v }))}
                >
                  <option value="id">🇮🇩 Bahasa Indonesia</option>
                  <option value="en">🇬🇧 English</option>
                </GoldSelect>
              </div>
              <div>
                <label className="text-xs text-muted-foreground mb-1.5 block font-medium">Mode Default</label>
                <GoldSelect
                  value={prefs.default_mode}
                  onChange={(v) => setPrefs((p) => ({ ...p, default_mode: v }))}
                >
                  <option value="simple">Simple Mode</option>
                  <option value="advanced">Advanced Mode</option>
                </GoldSelect>
              </div>
              <div>
                <label className="text-xs text-muted-foreground mb-1.5 block font-medium">Jumlah Variasi</label>
                <GoldSelect
                  value={prefs.default_variations}
                  onChange={(v) => setPrefs((p) => ({ ...p, default_variations: parseInt(v) }))}
                >
                  <option value={1}>1 Variasi</option>
                  <option value={3}>3 Variasi</option>
                  <option value={5}>5 Variasi</option>
                </GoldSelect>
              </div>
            </div>
            <div className="flex justify-end">
              <SaveBtn loading={savingPrefs} onClick={handleSavePrefs} />
            </div>
          </>
        )}
      </SectionCard>

      {/* ── Notifikasi ── */}
      <SectionCard
        icon={<Bell className="w-5 h-5" />}
        title="Notifikasi"
        description="Pengaturan email dan pemberitahuan akun."
        accent="#06b6d4"
      >
        <label className="flex items-center justify-between cursor-pointer">
          <div>
            <p className="text-sm font-medium">Notifikasi Email</p>
            <p className="text-xs text-muted-foreground mt-0.5">Update produk dan tips generate prompt</p>
          </div>
          <Toggle
            checked={prefs.email_notifications}
            onChange={() => setPrefs((p) => ({ ...p, email_notifications: !p.email_notifications }))}
          />
        </label>
        <div className="flex justify-end">
          <SaveBtn loading={savingPrefs} onClick={handleSavePrefs} />
        </div>
      </SectionCard>
    </div>
  );
}
