"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import ControlCenterNav from "@/components/layout/ControlCenterNav";
import Badge from "@/components/ui/Badge";
import Button from "@/components/ui/Button";
import Card from "@/components/ui/Card";
import PageHeader from "@/components/ui/PageHeader";
import SuperAdminUsersDashboard from "@/components/users/SuperAdminUsersDashboard";

type Role = "super_admin" | "owner";
type Row = {
  id: string;
  username: string;
  role: string;
  ownerId: string | null;
  status: string;
  passwordSetAt: string | null;
  createdAt: string;
  updatedAt: string;
  ownedShops: Array<{ shopId: string }>;
};
type ShopOption = { shopId: string; shopName: string | null; connected: boolean };
type Draft = { username: string; password: string };

function dateLabel(value: string | null) {
  if (!value) return "Belum pernah";
  return new Intl.DateTimeFormat("id-ID", { dateStyle: "medium", timeStyle: "short" }).format(new Date(value));
}

async function jsonRequest(url: string, init: RequestInit) {
  const response = await fetch(url, { ...init, headers: { "Content-Type": "application/json", ...(init.headers || {}) } });
  const json = (await response.json().catch(() => null)) as { ok?: boolean; error?: string } | null;
  if (!response.ok || !json?.ok) throw new Error(json?.error || "Operasi akun gagal.");
}

export default function UsersPageClient(props: { currentRole: Role; rows: Row[]; shops: ShopOption[]; dashboard?: boolean }) {
  if (props.currentRole === "super_admin") return <SuperAdminUsersDashboard dashboard={props.dashboard} rows={props.rows} shops={props.shops} />;
  return <OwnerStaffManager rows={props.rows} dashboard={props.dashboard} />;
}

function OwnerStaffManager({ rows, dashboard = false }: { rows: Row[]; dashboard?: boolean }) {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [drafts, setDrafts] = useState<Record<string, Draft>>({});
  const [busy, setBusy] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [message, setMessage] = useState<{ error: boolean; text: string } | null>(null);
  const noun = "Staff";

  function draft(row: Row) {
    return drafts[row.id] || { username: row.username, password: "" };
  }

  async function createAccount() {
    setBusy("create"); setMessage(null);
    try {
      await jsonRequest("/api/users", { method: "POST", body: JSON.stringify({ username, password }) });
      setUsername(""); setPassword(""); setMessage({ error: false, text: `${noun} berhasil dibuat.` }); router.refresh();
    } catch (error) { setMessage({ error: true, text: error instanceof Error ? error.message : "Gagal membuat akun." }); }
    finally { setBusy(null); }
  }

  async function updateAccount(row: Row, changes: { username?: string; password?: string; status?: string }) {
    setBusy(row.id); setMessage(null);
    try {
      await jsonRequest("/api/users", { method: "PATCH", body: JSON.stringify({ id: row.id, ...changes }) });
      setDrafts((state) => ({ ...state, [row.id]: { username: changes.username || row.username, password: "" } }));
      setMessage({ error: false, text: `${noun} ${row.username} berhasil diperbarui.` }); router.refresh();
    } catch (error) { setMessage({ error: true, text: error instanceof Error ? error.message : "Gagal memperbarui akun." }); }
    finally { setBusy(null); }
  }

  async function removeAccount(row: Row) {
    if (confirmDelete !== row.id) { setConfirmDelete(row.id); setMessage({ error: true, text: `Klik Hapus sekali lagi untuk menghapus Staff ${row.username}.` }); return; }
    setBusy(row.id); setMessage(null);
    try { await jsonRequest("/api/users", { method: "DELETE", body: JSON.stringify({ id: row.id }) }); setConfirmDelete(null); setMessage({ error: false, text: `Staff ${row.username} dihapus.` }); router.refresh(); }
    catch (error) { setMessage({ error: true, text: error instanceof Error ? error.message : "Gagal menghapus Staff." }); }
    finally { setBusy(null); }
  }

  return <div className="space-y-5">
    <PageHeader eyebrow={dashboard ? "Akun" : "Toko & Sistem"} title="Karyawan / Staff" description="Kelola akun Staff yang berada langsung di bawah Owner Anda." />
    {!dashboard ? <ControlCenterNav /> : null}
    {message ? <div className={`rounded-xl border p-3 text-sm font-semibold ${message.error ? "border-rose-200 bg-rose-50 text-rose-800" : "border-emerald-200 bg-emerald-50 text-emerald-800"}`}>{message.text}</div> : null}
    <Card title={`Tambah ${noun}`} description="Username harus unik dan password minimal 8 karakter.">
      <div className="grid gap-3 md:grid-cols-2">
        <label><span className="muted-label">Username {noun}</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 px-3 py-2.5 text-sm" value={username} onChange={(event) => setUsername(event.target.value)} /></label>
        <label><span className="muted-label">Password awal</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 px-3 py-2.5 text-sm" minLength={8} type="password" value={password} onChange={(event) => setPassword(event.target.value)} /></label>
        <div className="flex justify-end md:col-span-2"><Button variant="primary" loading={busy === "create"} onClick={createAccount}>Tambah {noun}</Button></div>
      </div>
    </Card>
    <Card title={`Daftar ${noun}`} description={`${rows.length} akun terdaftar. Password baru dikosongkan jika tidak ingin direset.`}>
      <div className="grid gap-3">
        {rows.map((row) => { const value = draft(row); return <div className="rounded-xl border border-slate-200 p-4" key={row.id}>
          <div className="flex flex-wrap items-start justify-between gap-3"><div><div className="flex items-center gap-2"><strong>{row.username}</strong><Badge tone={row.status === "active" ? "success" : "danger"}>{row.status === "active" ? "Aktif" : "Nonaktif"}</Badge></div><div className="mt-1 text-xs text-slate-500">Dibuat {dateLabel(row.createdAt)} · Password {dateLabel(row.passwordSetAt)}</div></div><Badge tone="neutral">{noun}</Badge></div>
          <div className="mt-4 grid gap-3 md:grid-cols-[1fr_1fr_auto_auto]">
            <label><span className="muted-label">Username</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" value={value.username} onChange={(event) => setDrafts((state) => ({ ...state, [row.id]: { ...value, username: event.target.value } }))} /></label>
            <label><span className="muted-label">Reset password</span><input className="mt-1.5 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Kosongkan jika tetap" type="password" value={value.password} onChange={(event) => setDrafts((state) => ({ ...state, [row.id]: { ...value, password: event.target.value } }))} /></label>
            <Button className="self-end" loading={busy === row.id} onClick={() => updateAccount(row, { username: value.username, ...(value.password ? { password: value.password } : {}) })}>Simpan</Button>
            <Button className="self-end" variant={row.status === "active" ? "danger" : "primary"} loading={busy === row.id} onClick={() => updateAccount(row, { status: row.status === "active" ? "inactive" : "active" })}>{row.status === "active" ? "Nonaktifkan" : "Aktifkan"}</Button>
          </div>
          <div className="mt-3 flex justify-end"><Button variant="danger" loading={busy === row.id} onClick={() => removeAccount(row)}>{confirmDelete === row.id ? "Konfirmasi hapus" : "Hapus Staff"}</Button></div>
        </div>; })}
        {rows.length === 0 ? <div className="rounded-xl border border-dashed border-slate-200 p-8 text-center text-sm text-slate-500">Belum ada akun {noun}.</div> : null}
      </div>
    </Card>
  </div>;
}
