"use client";

import { useMemo, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/Icon";
import { api } from "@/lib/client";
import { useT } from "@/components/providers";

export interface AdminUserRow {
  id: number;
  username: string;
  full_name: string;
  email: string | null;
  is_active: boolean;
  must_change_password: boolean;
  is_demo: boolean;
  locked_until: string | null;
  last_login_at: string | null;
  created_at: string | null;
  roles: { code: string; nameAr: string }[];
}

export interface AdminRoleRow {
  id: string;
  code: string;
  name_ar: string;
  is_enabled: boolean;
  governance_confirmed: boolean;
  requires_scope: boolean;
  active_assignments: number;
}

const GOVERNORATES: { id: number; name_ar: string }[] = [
  { id: 1, name_ar: "القاهرة" }, { id: 2, name_ar: "الإسكندرية" }, { id: 3, name_ar: "بورسعيد" },
  { id: 4, name_ar: "السويس" }, { id: 5, name_ar: "دمياط" }, { id: 6, name_ar: "الدقهلية" },
  { id: 7, name_ar: "الشرقية" }, { id: 8, name_ar: "القليوبية" }, { id: 9, name_ar: "كفر الشيخ" },
  { id: 10, name_ar: "الغربية" }, { id: 11, name_ar: "المنوفية" }, { id: 12, name_ar: "البحيرة" },
  { id: 13, name_ar: "الإسماعيلية" }, { id: 14, name_ar: "الجيزة" }, { id: 15, name_ar: "بني سويف" },
  { id: 16, name_ar: "الفيوم" }, { id: 17, name_ar: "المنيا" }, { id: 18, name_ar: "أسيوط" },
  { id: 19, name_ar: "سوهاج" }, { id: 20, name_ar: "قنا" }, { id: 21, name_ar: "الأقصر" },
  { id: 22, name_ar: "أسوان" }, { id: 23, name_ar: "البحر الأحمر" }, { id: 24, name_ar: "الوادي الجديد" },
  { id: 25, name_ar: "مطروح" }, { id: 26, name_ar: "شمال سيناء" }, { id: 27, name_ar: "جنوب سيناء" },
];

function RoleChip({ code, nameAr }: { code: string; nameAr: string }) {
  const demo = code.startsWith("demo_perm_");
  return (
    <span
      className={`inline-block rounded-full px-2.5 py-0.5 text-[11px] font-bold ${
        demo ? "bg-amber-50 text-amber-700" : "bg-bousla-50 text-bousla-800"
      }`}
    >
      {nameAr}
    </span>
  );
}

export function UsersAdmin({ initialUsers, roles }: { initialUsers: AdminUserRow[]; roles: AdminRoleRow[] }) {
  const router = useRouter();
  const [users, setUsers] = useState(initialUsers);
  const [busyId, setBusyId] = useState<number | null>(null);
  const [message, setMessage] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
  const { t } = useT();

  const assignableRoles = useMemo(() => roles.filter((r) => r.is_enabled && r.code !== "system_admin"), [roles]);

  async function refresh() {
    const res = await api<{ items: AdminUserRow[] }>("/api/admin/users?pageSize=50");
    if (res.status === 200 && res.data) setUsers(res.data.items);
    router.refresh();
  }

  async function run(id: number, fn: () => Promise<{ status: number; error: string | null }>, okText: string) {
    setBusyId(id);
    setMessage(null);
    const r = await fn();
    setBusyId(null);
    if (r.status >= 200 && r.status < 300) {
      setMessage({ kind: "ok", text: okText });
      await refresh();
    } else {
      setMessage({ kind: "err", text: r.error ?? t.users.opFailed });
    }
  }

  async function toggleActivation(u: AdminUserRow) {
    const reason = window.prompt(
      u.is_active ? t.users.deactivatePrompt(u.full_name) : t.users.activatePrompt(u.full_name),
    );
    if (!reason || reason.trim().length < 3) return;
    await run(u.id, () => api(`/api/admin/users/${u.id}/activation`, "PATCH", { activate: !u.is_active, reason }), t.users.statusUpdated);
  }

  async function assignRole(u: AdminUserRow) {
    const roleOptions = assignableRoles
      .map((r) => `${r.code} — ${r.name_ar}${r.requires_scope ? t.users.scopeHint : ""}${r.governance_confirmed ? "" : t.users.notConfirmed}`)
      .join("\n");
    const roleCode = window.prompt(t.users.assignPrompt(u.full_name, roleOptions));
    if (!roleCode) return;
    const role = assignableRoles.find((r) => r.code === roleCode.trim());
    if (!role) {
      setMessage({ kind: "err", text: t.users.invalidRole });
      return;
    }
    const reason = window.prompt(t.users.assignReason);
    if (!reason || reason.trim().length < 5) return;

    let governorateIds: number[] | undefined;
    if (role.requires_scope) {
      const govInput = window.prompt(t.users.scopePrompt(GOVERNORATES.map((g) => `${g.id}=${g.name_ar}`).join("، ")));
      if (!govInput) return;
      governorateIds = govInput.split(/[,،]/).map((s) => Number.parseInt(s.trim(), 10)).filter((n) => Number.isInteger(n) && n > 0);
      if (governorateIds.length === 0) {
        setMessage({ kind: "err", text: t.users.needGovernorate });
        return;
      }
    }

    let validUntil: string | null | undefined;
    validUntil = window.prompt("صلاحية الإسناد حتى تاريخ (اختياري — YYYY-MM-DD، فارغ = دائم):");
    if (validUntil === null) return;
    validUntil = validUntil.trim() || null;

    const body: Record<string, unknown> = { roleCode: role.code, reason, validUntil };
    if (governorateIds) body.governorateIds = governorateIds;
    if (!role.governance_confirmed) {
      const bypass = window.confirm(t.users.bypassConfirm);
      if (!bypass) return;
      body.allowUnconfirmedRole = true;
    }

    await run(u.id, () => api(`/api/admin/users/${u.id}/roles`, "POST", body), t.users.roleAssigned);
  }

  async function revokeRole(u: AdminUserRow, roleCode: string) {
    const reason = window.prompt(t.users.revokeReason);
    if (!reason || reason.trim().length < 5) return;
    await run(u.id, () => api(`/api/admin/users/${u.id}/roles/${roleCode}`, "DELETE", { reason }), t.users.roleRevoked);
  }

  async function createUser(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setMessage(null);
    const form = new FormData(e.currentTarget);
    const body = {
      username: String(form.get("username") ?? "").trim(),
      fullName: String(form.get("fullName") ?? "").trim(),
      email: String(form.get("email") ?? "").trim() || undefined,
      tempPassword: String(form.get("tempPassword") ?? ""),
    };
    const res = await api("/api/admin/users", "POST", body);
    if (res.status === 201) {
      setMessage({ kind: "ok", text: t.users.created });
      (e.target as HTMLFormElement).reset();
      await refresh();
    } else {
      setMessage({ kind: "err", text: res.error ?? t.users.createFailed });
    }
  }

  return (
    <div className="space-y-6">
      {message && (
        <div
          role="status"
          className={`rounded-lg border px-4 py-2.5 text-sm ${
            message.kind === "ok" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-red-200 bg-red-50 text-red-700"
          }`}
        >
          {message.text}
        </div>
      )}

      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="users" className="h-5 w-5 text-bousla-700" /> {t.users.createTitle}
        </h2>
        <form onSubmit={createUser} className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
          <div>
            <label htmlFor="f-username" className="mb-1 block text-xs font-bold text-slate-600">{t.users.username}</label>
            <input id="f-username" name="username" dir="ltr" required minLength={3} maxLength={64}
              pattern="[a-zA-Z0-9_.\-]+" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm text-left outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
          </div>
          <div>
            <label htmlFor="f-fullname" className="mb-1 block text-xs font-bold text-slate-600">{t.users.fullName}</label>
            <input id="f-fullname" name="fullName" required minLength={3} className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
          </div>
          <div>
            <label htmlFor="f-email" className="mb-1 block text-xs font-bold text-slate-600">{t.users.emailOptional}</label>
            <input id="f-email" name="email" type="email" dir="ltr" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm text-left outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
          </div>
          <div>
            <label htmlFor="f-temp" className="mb-1 block text-xs font-bold text-slate-600">{t.users.tempPassword}</label>
            <input id="f-temp" name="tempPassword" dir="ltr" required minLength={10} type="text"
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm text-left outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" />
          </div>
          <div className="flex items-end">
            <button type="submit" className="w-full rounded-lg bg-bousla-700 px-4 py-2 text-sm font-bold text-white transition hover:bg-bousla-800">
              {t.users.createBtn}
            </button>
          </div>
        </form>
      </section>

      <section className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-card">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[860px] text-sm">
            <thead>
              <tr className="border-b border-slate-200 bg-slate-50 text-right text-xs font-bold text-slate-500">
                <th className="px-4 py-3">{t.users.thUser}</th>
                <th className="px-4 py-3">{t.users.thStatus}</th>
                <th className="px-4 py-3">{t.users.thRoles}</th>
                <th className="px-4 py-3">{t.users.thLastLogin}</th>
                <th className="px-4 py-3">{t.users.thActions}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {users.map((u) => (
                <tr key={u.id} className="hover:bg-slate-50/60">
                  <td className="px-4 py-3">
                    <p className="font-bold text-slate-800" dir="auto">{u.full_name}</p>
                    <p className="text-xs text-slate-400" dir="ltr">{u.username}{u.email ? ` · ${u.email}` : ""}</p>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`rounded-full px-2.5 py-0.5 text-[11px] font-bold ${u.is_active ? "bg-emerald-50 text-emerald-700" : "bg-slate-100 text-slate-500"}`}>
                      {u.is_active ? t.users.active : t.users.inactive}
                    </span>
                    {u.is_demo && <span className="mr-1.5 rounded-full bg-amber-50 px-2 py-0.5 text-[11px] font-bold text-amber-700">DEMO</span>}
                    {u.locked_until && new Date(u.locked_until) > new Date() && (
                      <span className="mr-1.5 rounded-full bg-red-50 px-2 py-0.5 text-[11px] font-bold text-red-700">{t.users.locked}</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex flex-wrap gap-1.5">
                      {u.roles.length === 0 && <span className="text-xs text-slate-400">—</span>}
                      {u.roles.map((r) => (
                        <button
                          key={r.code}
                          onClick={() => revokeRole(u, r.code)}
                          disabled={busyId === u.id}
                          title={t.users.revokeHint}
                          className="transition hover:opacity-70 disabled:opacity-50"
                        >
                          <RoleChip code={r.code} nameAr={r.nameAr} />
                        </button>
                      ))}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500">
                    {u.last_login_at
                      ? new Intl.DateTimeFormat("ar-EG", { dateStyle: "short", timeStyle: "short", timeZone: "Africa/Cairo" }).format(new Date(u.last_login_at))
                      : "—"}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-2">
                      <button
                        onClick={() => assignRole(u)}
                        disabled={busyId === u.id}
                        className="rounded-lg border border-bousla-200 px-2.5 py-1 text-xs font-bold text-bousla-800 transition hover:bg-bousla-50 disabled:opacity-50"
                      >
                        {t.users.assignRole}
                      </button>
                      <button
                        onClick={() => toggleActivation(u)}
                        disabled={busyId === u.id}
                        className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-bold text-slate-600 transition hover:bg-slate-50 disabled:opacity-50"
                      >
                        {u.is_active ? t.users.deactivate : t.users.activate}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
