"use client";

import { useEffect, useMemo, useState } from "react";
import AdminShell from "@/shared/AdminShell";
import { useAppSelector } from "@/core/hook";
import type { AdminRole } from "@/core/authSlice";
import {
  useListAdminsQuery,
  useInviteAdminMutation,
  useSetAdminActiveMutation,
  useSetAdminRoleMutation,
  useDeleteAdminMutation,
} from "@/services/admin-service";
import { getApiErrorMessage } from "@/utils/apiError";

function formatDate(value: string | null): string {
  if (!value) return "—";
  const d = new Date(value);
  return Number.isNaN(d.getTime())
    ? value
    : d.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
}

export default function AdminUsersPage() {
  const me = useAppSelector((s) => s.auth.admin);
  const isSuper = me?.role === "super_admin";
  const [q, setQ] = useState("");
  const [debouncedQ, setDebouncedQ] = useState("");
  const [page, setPage] = useState(1);
  const [actionError, setActionError] = useState("");
  const [inviteOpen, setInviteOpen] = useState(false);

  useEffect(() => {
    const t = setTimeout(() => setDebouncedQ(q.trim()), 350);
    return () => clearTimeout(t);
  }, [q]);

  const { data, error, isFetching } = useListAdminsQuery({
    page,
    limit: 20,
    q: debouncedQ || undefined,
  });
  const [setAdminActive] = useSetAdminActiveMutation();
  const [setAdminRole] = useSetAdminRoleMutation();
  const [deleteAdmin] = useDeleteAdminMutation();

  const fetchErrorMsg = error ? getApiErrorMessage(error, "Failed to load admins") : "";

  const totalPages = useMemo(
    () => (data ? Math.max(1, Math.ceil(data.total / data.limit)) : 1),
    [data],
  );

  const onSetActive = async (id: number, is_active: boolean) => {
    setActionError("");
    try {
      await setAdminActive({ id, is_active }).unwrap();
    } catch (err) {
      setActionError(getApiErrorMessage(err, "Update failed"));
    }
  };

  const onSetRole = async (id: number, role: AdminRole) => {
    setActionError("");
    try {
      await setAdminRole({ id, role }).unwrap();
    } catch (err) {
      setActionError(getApiErrorMessage(err, "Role change failed"));
    }
  };

  const onDelete = async (id: number) => {
    if (!confirm("Delete this admin account?")) return;
    setActionError("");
    try {
      await deleteAdmin(id).unwrap();
    } catch (err) {
      setActionError(getApiErrorMessage(err, "Delete failed"));
    }
  };

  return (
    <AdminShell>
      <div className="mb-8 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <p className="text-[10px] uppercase tracking-[0.3em] text-[#d6ac63]">
            Manage
          </p>
          <h1 className="mt-2 text-2xl lg:text-3xl font-light text-black">
            Admin users
          </h1>
          <p className="mt-2 text-sm text-gray-600 font-light">
            {data ? `${data.total} admin${data.total === 1 ? "" : "s"}` : ""}
          </p>
        </div>
        <div className="flex flex-col gap-3 sm:flex-row">
          <input
            type="search"
            placeholder="Search name or email…"
            value={q}
            onChange={(e) => {
              setPage(1);
              setQ(e.target.value);
            }}
            className="border border-[#d6ac63]/30 bg-white px-4 py-2.5 text-sm focus:border-[#d6ac63] focus:outline-none w-full sm:w-72"
          />
          {isSuper ? (
            <button
              type="button"
              onClick={() => setInviteOpen(true)}
              className="bg-black text-white px-5 py-2.5 text-xs uppercase tracking-[0.2em] hover:bg-[#d6ac63] transition-colors"
            >
              Invite admin
            </button>
          ) : null}
        </div>
      </div>

      {(fetchErrorMsg || actionError) ? (
        <p className="mb-4 text-sm text-red-500">{fetchErrorMsg || actionError}</p>
      ) : null}

      <div className="border border-[#d6ac63]/15 bg-white overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead className="bg-[#fbf7f0] text-[10px] uppercase tracking-[0.2em] text-gray-600">
            <tr>
              <th className="px-4 py-3 text-left">Name</th>
              <th className="px-4 py-3 text-left">Email</th>
              <th className="px-4 py-3 text-left">Role</th>
              <th className="px-4 py-3 text-left">Status</th>
              <th className="px-4 py-3 text-left">Last login</th>
              <th className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            {isFetching ? (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-gray-500">
                  Loading…
                </td>
              </tr>
            ) : !data || data.admins.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-gray-500">
                  No admins found.
                </td>
              </tr>
            ) : (
              data.admins.map((a) => {
                const isSelf = me?.id === a.id;
                return (
                  <tr key={a.id} className="border-t border-[#d6ac63]/10 hover:bg-[#fbf7f0]/50">
                    <td className="px-4 py-3">
                      <p className="font-light text-black">{a.fullname}</p>
                      {!a.is_email_verified ? (
                        <p className="text-[10px] uppercase tracking-[0.2em] text-amber-600 mt-1">
                          Email not verified
                        </p>
                      ) : null}
                    </td>
                    <td className="px-4 py-3 text-gray-700">{a.email}</td>
                    <td className="px-4 py-3">
                      {isSuper && !isSelf ? (
                        <select
                          value={a.role}
                          onChange={(e) => onSetRole(a.id, e.target.value as AdminRole)}
                          className="border border-[#d6ac63]/30 bg-white px-2 py-1.5 text-xs uppercase tracking-wide"
                        >
                          <option value="admin">admin</option>
                          <option value="super_admin">super_admin</option>
                        </select>
                      ) : (
                        <span className="text-xs uppercase tracking-[0.2em] text-gray-700">
                          {a.role === "super_admin" ? "Super Admin" : "Admin"}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`inline-flex items-center border px-2.5 py-1 text-[10px] uppercase tracking-[0.15em] ${
                          a.is_active
                            ? "bg-green-50 text-green-700 border-green-200"
                            : "bg-gray-100 text-gray-700 border-gray-200"
                        }`}
                      >
                        {a.is_active ? "Active" : "Deactivated"}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-600 text-xs whitespace-nowrap">
                      {formatDate(a.last_login_at)}
                    </td>
                    <td className="px-4 py-3 text-right whitespace-nowrap">
                      {isSuper && !isSelf ? (
                        <>
                          <button
                            type="button"
                            onClick={() => onSetActive(a.id, !a.is_active)}
                            className="text-[10px] uppercase tracking-[0.2em] text-[#d6ac63] hover:underline mr-4"
                          >
                            {a.is_active ? "Deactivate" : "Activate"}
                          </button>
                          <button
                            type="button"
                            onClick={() => onDelete(a.id)}
                            className="text-[10px] uppercase tracking-[0.2em] text-red-600 hover:underline"
                          >
                            Delete
                          </button>
                        </>
                      ) : (
                        <span className="text-[10px] uppercase tracking-[0.2em] text-gray-400">
                          {isSelf ? "You" : "—"}
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      {data && data.total > data.limit ? (
        <div className="mt-6 flex items-center justify-between text-xs text-gray-600">
          <span>
            Page {data.page} of {totalPages}
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              disabled={data.page <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              className="border border-[#d6ac63]/30 px-4 py-2 uppercase tracking-wide disabled:opacity-40"
            >
              Prev
            </button>
            <button
              type="button"
              disabled={data.page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              className="border border-[#d6ac63]/30 px-4 py-2 uppercase tracking-wide disabled:opacity-40"
            >
              Next
            </button>
          </div>
        </div>
      ) : null}

      {inviteOpen ? (
        <InviteAdminModal onClose={() => setInviteOpen(false)} />
      ) : null}
    </AdminShell>
  );
}

function InviteAdminModal({ onClose }: { onClose: () => void }) {
  const [fullname, setFullname] = useState("");
  const [email, setEmail] = useState("");
  const [role, setRole] = useState<AdminRole>("admin");
  const [errorMsg, setErrorMsg] = useState("");
  const [inviteAdmin, { isLoading }] = useInviteAdminMutation();

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrorMsg("");
    try {
      await inviteAdmin({ fullname, email, role }).unwrap();
      onClose();
    } catch (err) {
      setErrorMsg(getApiErrorMessage(err, "Invitation failed"));
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
      <div className="w-full max-w-md bg-white border border-[#d6ac63]/30 p-6 lg:p-8">
        <div className="flex items-start justify-between mb-6">
          <div>
            <p className="text-[10px] uppercase tracking-[0.3em] text-[#d6ac63]">
              Invite
            </p>
            <h2 className="mt-1 text-lg font-light text-black">New admin</h2>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="text-gray-400 hover:text-black text-xl leading-none"
            aria-label="Close"
          >
            ×
          </button>
        </div>
        <form onSubmit={onSubmit} className="space-y-5">
          <div>
            <label className="block text-[10px] uppercase tracking-[0.2em] text-gray-500 mb-2">
              Full name
            </label>
            <input
              required
              value={fullname}
              onChange={(e) => setFullname(e.target.value)}
              className="block w-full border border-[#d6ac63]/30 bg-white px-4 py-3 text-sm focus:border-[#d6ac63] focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-[10px] uppercase tracking-[0.2em] text-gray-500 mb-2">
              Email
            </label>
            <input
              required
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="block w-full border border-[#d6ac63]/30 bg-white px-4 py-3 text-sm focus:border-[#d6ac63] focus:outline-none"
            />
          </div>
          <div>
            <label className="block text-[10px] uppercase tracking-[0.2em] text-gray-500 mb-2">
              Role
            </label>
            <select
              value={role}
              onChange={(e) => setRole(e.target.value as AdminRole)}
              className="block w-full border border-[#d6ac63]/30 bg-white px-4 py-3 text-sm focus:border-[#d6ac63] focus:outline-none"
            >
              <option value="admin">Admin</option>
              <option value="super_admin">Super admin</option>
            </select>
          </div>
          {errorMsg ? <p className="text-sm text-red-500">{errorMsg}</p> : null}
          <div className="flex gap-3">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 border border-[#d6ac63]/30 px-4 py-3 text-xs uppercase tracking-[0.2em] text-gray-700 hover:bg-[#fbf7f0]"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isLoading}
              className="flex-1 bg-black text-white px-4 py-3 text-xs uppercase tracking-[0.2em] hover:bg-[#d6ac63] transition-colors disabled:opacity-60"
            >
              {isLoading ? "Sending…" : "Send invite"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
