"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Search, RefreshCw, Loader2,
  Edit2, Check, X, ChevronLeft, ChevronRight, Crown,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { formatDate } from "@/lib/utils";

interface UserRow {
  id: string;
  email: string;
  full_name: string | null;
  plan: "free" | "pro" | "enterprise";
  role: "user" | "admin";
  usage_count: number;
  usage_limit: number;
  total_generations: number;
  created_at: string;
}

// ─── Inline Edit Select ───────────────────────────────────────────────────────
function EditableSelect({
  value, options, onSave, labelMap,
}: {
  value: string;
  options: string[];
  onSave: (v: string) => Promise<void>;
  labelMap?: Record<string, string>;
}) {
  const [editing, setSaving2] = useState(false);
  const [editing2, setEditing] = useState(false);
  const [local, setLocal] = useState(value);
  const [saving, setSaving] = useState(false);

  async function handleSave() {
    if (local === value) { setEditing(false); return; }
    setSaving(true);
    try { await onSave(local); setEditing(false); }
    finally { setSaving(false); }
  }

  if (!editing2) {
    return (
      <button onClick={() => setEditing(true)} className="flex items-center gap-1 group text-left">
        <span>{labelMap?.[value] ?? value}</span>
        <Edit2 className="w-3 h-3 opacity-0 group-hover:opacity-50 transition-opacity text-amber-400" />
      </button>
    );
  }

  return (
    <div className="flex items-center gap-1">
      <select
        value={local}
        onChange={(e) => setLocal(e.target.value)}
        className="text-xs px-1.5 py-0.5 rounded bg-accent focus:outline-none"
        style={{ border: "1px solid rgba(212,175,55,0.3)" }}
        autoFocus
      >
        {options.map((o) => (
          <option key={o} value={o}>{labelMap?.[o] ?? o}</option>
        ))}
      </select>
      {saving
        ? <Loader2 className="w-3.5 h-3.5 animate-spin text-amber-400" />
        : <>
            <button onClick={handleSave} className="text-emerald-400 hover:text-emerald-300"><Check className="w-3.5 h-3.5" /></button>
            <button onClick={() => { setLocal(value); setEditing(false); }} className="text-red-400 hover:text-red-300"><X className="w-3.5 h-3.5" /></button>
          </>}
    </div>
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────
export default function AdminUsersPage() {
  const [users, setUsers] = useState<UserRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 20;

  useEffect(() => {
    const t = setTimeout(() => { setDebouncedSearch(search); setPage(1); }, 400);
    return () => clearTimeout(t);
  }, [search]);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (debouncedSearch) params.set("search", debouncedSearch);
      const res = await fetch(`/api/admin/users?${params}`);
      const data = await res.json();
      setUsers(data.data ?? []);
      setTotal(data.count ?? 0);
    } finally {
      setLoading(false);
    }
  }, [page, debouncedSearch]);

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

  async function updateUser(id: string, updates: Record<string, unknown>) {
    const res = await fetch("/api/admin/users", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, ...updates }),
    });
    if (!res.ok) { toast.error("Gagal update user"); return false; }
    toast.success("User diperbarui");
    setUsers((prev) => prev.map((u) => u.id === id ? { ...u, ...updates } : u));
    return true;
  }

  const totalPages = Math.ceil(total / limit);

  return (
    <div className="max-w-7xl mx-auto space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Manajemen User</h1>
          <p className="text-sm text-muted-foreground mt-0.5">{total.toLocaleString()} user terdaftar</p>
        </div>
        <button onClick={fetchUsers} 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>

      {/* Search */}
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Cari email atau nama..."
          className="w-full pl-9 pr-4 py-2 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>

      {/* Table */}
      <div className="gold-card rounded-2xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-xs text-muted-foreground"
                style={{ borderBottom: "1px solid rgba(212,175,55,0.12)", background: "rgba(212,175,55,0.03)" }}>
                <th className="text-left px-4 py-3 font-medium">User</th>
                <th className="text-left px-4 py-3 font-medium">Role</th>
                <th className="text-left px-4 py-3 font-medium">Plan</th>
                <th className="text-left px-4 py-3 font-medium">Usage</th>
                <th className="text-left px-4 py-3 font-medium">Total Gen</th>
                <th className="text-left px-4 py-3 font-medium">Bergabung</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center">
                    <Loader2 className="w-6 h-6 animate-spin mx-auto text-amber-400/50" />
                  </td>
                </tr>
              ) : users.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center text-muted-foreground text-sm">
                    Tidak ada user ditemukan
                  </td>
                </tr>
              ) : users.map((u) => (
                <tr key={u.id} className="transition-colors hover:bg-white/[0.02]"
                  style={{ borderTop: "1px solid rgba(212,175,55,0.07)" }}>

                  {/* User */}
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2.5">
                      <div className={cn(
                        "w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0",
                      )} style={{
                        background: u.role === "admin"
                          ? "linear-gradient(135deg, #d4af37, #b8860b)"
                          : "linear-gradient(135deg, #7c3aed, #06b6d4)",
                        boxShadow: u.role === "admin" ? "0 0 8px rgba(212,175,55,0.3)" : "none",
                      }}>
                        <span className="text-white">{(u.full_name ?? u.email)[0].toUpperCase()}</span>
                      </div>
                      <div>
                        <p className="font-medium">{u.full_name ?? <span className="text-muted-foreground italic text-xs">no name</span>}</p>
                        <p className="text-xs text-muted-foreground">{u.email}</p>
                      </div>
                    </div>
                  </td>

                  {/* Role — inline edit */}
                  <td className="px-4 py-3 text-xs">
                    <EditableSelect
                      value={u.role}
                      options={["user", "admin"]}
                      labelMap={{ user: "User", admin: "Admin" }}
                      onSave={async (v) => { await updateUser(u.id, { role: v }); }}
                    />
                  </td>

                  {/* Plan — inline edit */}
                  <td className="px-4 py-3 text-xs">
                    <EditableSelect
                      value={u.plan}
                      options={["free", "pro", "enterprise"]}
                      onSave={async (v) => { await updateUser(u.id, { plan: v }); }}
                    />
                  </td>

                  {/* Usage bar */}
                  <td className="px-4 py-3">
                    <div className="min-w-[110px]">
                      <div className="flex justify-between text-xs mb-1">
                        <span className="tabular-nums">{u.usage_count}</span>
                        <span className="text-muted-foreground tabular-nums">/{u.usage_limit}</span>
                      </div>
                      <div className="h-1.5 rounded-full overflow-hidden"
                        style={{ background: "rgba(212,175,55,0.08)", border: "1px solid rgba(212,175,55,0.1)" }}>
                        <div
                          className="h-full rounded-full transition-all"
                          style={{
                            width: `${Math.min((u.usage_count / u.usage_limit) * 100, 100)}%`,
                            background: (u.usage_count / u.usage_limit) > 0.9
                              ? "linear-gradient(90deg, #f59e0b, #ef4444)"
                              : (u.usage_count / u.usage_limit) > 0.7
                              ? "#f59e0b"
                              : "linear-gradient(90deg, #7c3aed, #06b6d4)",
                          }}
                        />
                      </div>
                    </div>
                  </td>

                  {/* Total gen */}
                  <td className="px-4 py-3 tabular-nums font-semibold text-amber-300/80">
                    {u.total_generations.toLocaleString()}
                  </td>

                  {/* Date */}
                  <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
                    {formatDate(u.created_at)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="px-4 py-3 flex items-center justify-between text-xs"
            style={{ borderTop: "1px solid rgba(212,175,55,0.1)" }}>
            <span className="text-muted-foreground">Hal {page} dari {totalPages} ({total} user)</span>
            <div className="flex gap-1">
              <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1}
                className="w-8 h-8 rounded flex items-center justify-center hover:bg-white/5 disabled:opacity-40 transition-colors"
                style={{ border: "1px solid rgba(212,175,55,0.15)" }}>
                <ChevronLeft className="w-4 h-4" />
              </button>
              <button onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={page === totalPages}
                className="w-8 h-8 rounded flex items-center justify-center hover:bg-white/5 disabled:opacity-40 transition-colors"
                style={{ border: "1px solid rgba(212,175,55,0.15)" }}>
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Legend */}
      <div className="flex gap-4 text-xs text-muted-foreground">
        <span className="flex items-center gap-1"><Edit2 className="w-3 h-3 text-amber-400" /> Hover Role/Plan untuk edit inline</span>
        <span>🔴 Usage &gt;90%</span>
        <span>🟡 Usage &gt;70%</span>
        <span style={{ color: "rgba(212,175,55,0.6)" }}>
          <Crown className="w-3 h-3 inline mr-0.5" /> Avatar emas = admin
        </span>
      </div>
    </div>
  );
}
