"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Users,
  UserPlus,
  Pencil,
  Trash2,
  ToggleLeft,
  ToggleRight,
  AlertCircle,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { useTranslation } from "@/lib/hooks/use-translation";
import { tToast } from "@/lib/utils/translated-toast";
import { adminApi } from "@/lib/api/client";
import type { User, UserRole, UserStatus, PageResponse } from "@/types";

/* ───── Role / Status config ───── */

const ALL_ROLES = ["ALL", "AUTHOR", "REVIEWER", "ADMIN"] as const;

const roleBadgeColor: Record<string, string> = {
  AUTHOR: "bg-blue-100 text-blue-700",
  REVIEWER: "bg-purple-100 text-purple-700",
  ADMIN: "bg-indigo-100 text-indigo-700",
};

const statusBadgeColor: Record<string, string> = {
  ACTIVE: "bg-green-100 text-green-700",
  INACTIVE: "bg-gray-100 text-gray-700",
  SUSPENDED: "bg-red-100 text-red-700",
};

/* ───── Empty form state ───── */

const emptyForm = {
  nameHi: "",
  nameEn: "",
  email: "",
  phone: "",
  role: "AUTHOR" as UserRole,
  designation: "",
  institution: "",
  department: "",
};

/* ───── Page ───── */

export default function AdminUsers() {
  const queryClient = useQueryClient();
  const { t: cms, language } = useTranslation(["ADMIN_USERS", "STATUS_LABELS", "COMMON"]);

  const [roleFilter, setRoleFilter] = useState<string>("ALL");
  const [page, setPage] = useState(0);
  const pageSize = 10;

  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editUser, setEditUser] = useState<User | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<User | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [createdUserInfo, setCreatedUserInfo] = useState<{ nameEn: string; email: string; temporaryPassword: string } | null>(null);

  /* ─── Query ─── */

  const params: Record<string, unknown> = { page, size: pageSize };
  if (roleFilter !== "ALL") params.role = roleFilter;

  const { data, isLoading, error } = useQuery<PageResponse<User>>({
    queryKey: ["admin-users", roleFilter, page],
    queryFn: async () => {
      const res = await adminApi.users(params);
      return res.data;
    },
  });

  const users = data?.content ?? [];
  const totalPages = data?.totalPages ?? 0;

  /* ─── Mutations ─── */

  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => adminApi.createUser(data),
    onSuccess: (response) => {
      const created = response.data;
      setShowCreateModal(false);
      setForm(emptyForm);
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      if (created.temporaryPassword) {
        setCreatedUserInfo({
          nameEn: created.nameEn ?? "",
          email: created.email ?? "",
          temporaryPassword: created.temporaryPassword,
        });
      } else {
        tToast("success", "admin_users.user_created", "User created");
      }
    },
    onError: () => tToast("error", "admin_users.create_failed", "Failed to create user"),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
      adminApi.updateUser(id, data),
    onSuccess: () => {
      tToast("success", "admin_users.user_updated", "User updated");
      setEditUser(null);
      setForm(emptyForm);
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
    },
    onError: () => tToast("error", "admin_users.update_failed", "Failed to update user"),
  });

  const toggleMutation = useMutation({
    mutationFn: (id: string) => adminApi.toggleUser(id),
    onSuccess: () => {
      tToast("success", "admin_users.status_toggled", "Status toggled");
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
    },
    onError: () => tToast("error", "admin_users.toggle_failed", "Failed to toggle status"),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => adminApi.deleteUser(id),
    onSuccess: () => {
      tToast("success", "admin_users.user_deleted", "User deleted");
      setDeleteConfirm(null);
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
    },
    onError: () => tToast("error", "admin_users.delete_failed", "Failed to delete user"),
  });

  /* ─── Helpers ─── */

  function openCreate() {
    setForm(emptyForm);
    setShowCreateModal(true);
  }

  function openEdit(user: User) {
    setForm({
      nameHi: user.nameHi,
      nameEn: user.nameEn,
      email: user.email,
      phone: user.phone ?? "",
      role: user.role,
      designation: user.designation ?? "",
      institution: user.institution ?? "",
      department: user.department ?? "",
    });
    setEditUser(user);
  }

  function handleSubmitCreate() {
    const payload: Record<string, unknown> = { ...form };
    if (!payload.phone) delete payload.phone;
    if (!payload.designation) delete payload.designation;
    if (!payload.institution) delete payload.institution;
    if (!payload.department) delete payload.department;
    createMutation.mutate(payload);
  }

  function handleSubmitEdit() {
    if (!editUser) return;
    const payload: Record<string, unknown> = { ...form };
    if (!payload.phone) delete payload.phone;
    if (!payload.designation) delete payload.designation;
    if (!payload.institution) delete payload.institution;
    if (!payload.department) delete payload.department;
    updateMutation.mutate({ id: editUser.id, data: payload });
  }

  function updateField(field: string, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  function displayName(user: User) {
    return language === "hi" ? user.nameHi : user.nameEn;
  }

  /* ───── Render ───── */

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {cms("ADMIN_USERS.users_header.title", "User Management")}
          </h1>
          <p className="text-gray-500 text-sm mt-1">
            {cms("ADMIN_USERS.users_header.subtitle", "View & manage all users")}
          </p>
        </div>

        <button
          onClick={openCreate}
          className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition"
        >
          <UserPlus className="h-4 w-4" />
          {cms("ADMIN_USERS.users_actions.create", "Create User")}
        </button>
      </div>

      {/* Role filter tabs */}
      <div className="flex flex-wrap gap-2 mb-6">
        {ALL_ROLES.map((role) => (
          <button
            key={role}
            onClick={() => {
              setRoleFilter(role);
              setPage(0);
            }}
            className={cn(
              "rounded-full px-4 py-1.5 text-sm font-medium transition",
              roleFilter === role
                ? "bg-indigo-600 text-white shadow-sm"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            )}
          >
            {role === "ALL" ? cms("COMMON.labels.all", "All") : cms(`STATUS_LABELS.role.${role.toLowerCase()}`, role)}
          </button>
        ))}
      </div>

      {/* Loading / Error */}
      {isLoading && (
        <div className="flex items-center justify-center py-20">
          <p className="text-gray-500 text-lg">{cms("COMMON.loading", "Loading...")}</p>
        </div>
      )}

      {error && !isLoading && (
        <div className="flex items-center justify-center py-20">
          <div className="text-center">
            <AlertCircle className="mx-auto h-10 w-10 text-red-400 mb-2" />
            <p className="text-red-600">
              {cms("COMMON.error_loading", "Error loading data")}
            </p>
          </div>
        </div>
      )}

      {/* Users table */}
      {!isLoading && !error && (
        <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
          {users.length === 0 ? (
            <div className="px-5 py-16 text-center text-gray-500">
              <Users className="mx-auto h-10 w-10 text-gray-300 mb-3" />
              <p>{cms("ADMIN_USERS.users_table.no_users", "No users found")}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-left">
                  <tr>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_USERS.users_table.col_name", "Name")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_USERS.users_table.col_email", "Email")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_USERS.users_table.col_role", "Role")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_USERS.users_table.col_status", "Status")}
                    </th>
                    <th className="px-5 py-3 font-medium text-gray-500">
                      {cms("ADMIN_USERS.users_table.col_actions", "Actions")}
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {users.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50 transition">
                      <td className="px-5 py-4">
                        <div className="font-medium text-gray-900">
                          {displayName(user)}
                        </div>
                        {user.institution && (
                          <div className="text-xs text-gray-400 mt-0.5">
                            {user.institution}
                          </div>
                        )}
                      </td>
                      <td className="px-5 py-4 text-gray-600">{user.email}</td>
                      <td className="px-5 py-4">
                        <span
                          className={cn(
                            "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                            roleBadgeColor[user.role] ?? "bg-gray-100 text-gray-700"
                          )}
                        >
                          {cms(`STATUS_LABELS.role.${user.role.toLowerCase()}`, user.role)}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        <span
                          className={cn(
                            "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                            statusBadgeColor[user.status] ?? "bg-gray-100 text-gray-700"
                          )}
                        >
                          {cms(`STATUS_LABELS.user.${user.status.toLowerCase()}`, user.status)}
                        </span>
                      </td>
                      <td className="px-5 py-4">
                        <div className="flex flex-wrap gap-1.5">
                          <button
                            onClick={() => openEdit(user)}
                            className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
                          >
                            <Pencil className="h-3.5 w-3.5" />
                            {cms("ADMIN_USERS.users_actions.edit", "Edit")}
                          </button>
                          <button
                            onClick={() => toggleMutation.mutate(user.id)}
                            disabled={toggleMutation.isPending}
                            className="inline-flex items-center gap-1 rounded-md bg-amber-50 px-2.5 py-1.5 text-xs font-medium text-amber-700 hover:bg-amber-100 transition disabled:opacity-50"
                          >
                            {user.status === "ACTIVE" ? (
                              <ToggleRight className="h-3.5 w-3.5" />
                            ) : (
                              <ToggleLeft className="h-3.5 w-3.5" />
                            )}
                            {user.status === "ACTIVE"
                              ? cms("ADMIN_USERS.users_actions.deactivate", "Deactivate")
                              : cms("ADMIN_USERS.users_actions.activate", "Activate")}
                          </button>
                          <button
                            onClick={() => setDeleteConfirm(user)}
                            className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2.5 py-1.5 text-xs font-medium text-red-700 hover:bg-red-100 transition"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                            {cms("ADMIN_USERS.users_actions.delete", "Delete")}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between border-t border-gray-200 px-5 py-3">
              <p className="text-sm text-gray-500">
                {cms("ADMIN_USERS.users_table.page_label", "Page")} {page + 1} / {totalPages}
                {data?.totalElements != null && (
                  <span className="ml-2">
                    ({data.totalElements} {cms("ADMIN_USERS.users_table.total_label", "total")})
                  </span>
                )}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(0, p - 1))}
                  disabled={page === 0}
                  className="inline-flex items-center gap-1 rounded-md border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="h-4 w-4" />
                  {cms("ADMIN_USERS.users_table.prev", "Previous")}
                </button>
                <button
                  onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
                  disabled={page >= totalPages - 1}
                  className="inline-flex items-center gap-1 rounded-md border border-gray-300 px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {cms("ADMIN_USERS.users_table.next", "Next")}
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ─── Create User Modal ─── */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-lg bg-white rounded-xl shadow-xl p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              {cms("ADMIN_USERS.users_modal.create_title", "Create User")}
            </h3>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.name_hi", "Name (Hindi)")} *
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.nameHi}
                  onChange={(e) => updateField("nameHi", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.name_en", "Name (English)")} *
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.nameEn}
                  onChange={(e) => updateField("nameEn", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.email", "Email")} *
                </label>
                <input
                  type="email"
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.email}
                  onChange={(e) => updateField("email", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.phone", "Phone")}
                </label>
                <input
                  type="tel"
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.phone}
                  onChange={(e) => updateField("phone", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.role", "Role")} *
                </label>
                <select
                  className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.role}
                  onChange={(e) => updateField("role", e.target.value)}
                >
                  <option value="AUTHOR">{cms("STATUS_LABELS.role.author", "Author")}</option>
                  <option value="REVIEWER">{cms("STATUS_LABELS.role.reviewer", "Reviewer")}</option>
                  <option value="ADMIN">{cms("STATUS_LABELS.role.admin", "Admin")}</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.designation", "Designation")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.designation}
                  onChange={(e) => updateField("designation", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.institution", "Institution")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.institution}
                  onChange={(e) => updateField("institution", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.department", "Department")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.department}
                  onChange={(e) => updateField("department", e.target.value)}
                />
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => {
                  setShowCreateModal(false);
                  setForm(emptyForm);
                }}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={handleSubmitCreate}
                disabled={!form.nameHi || !form.nameEn || !form.email || createMutation.isPending}
                className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 disabled:opacity-50 transition"
              >
                {createMutation.isPending ? "..." : cms("ADMIN_USERS.users_modal.create_btn", "Create")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Edit User Modal ─── */}
      {editUser && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-lg bg-white rounded-xl shadow-xl p-6 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              {cms("ADMIN_USERS.users_modal.edit_title", "Edit User")}
            </h3>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.name_hi", "Name (Hindi)")} *
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.nameHi}
                  onChange={(e) => updateField("nameHi", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.name_en", "Name (English)")} *
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.nameEn}
                  onChange={(e) => updateField("nameEn", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.email", "Email")} *
                </label>
                <input
                  type="email"
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.email}
                  onChange={(e) => updateField("email", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.phone", "Phone")}
                </label>
                <input
                  type="tel"
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.phone}
                  onChange={(e) => updateField("phone", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.role", "Role")} *
                </label>
                <select
                  className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.role}
                  onChange={(e) => updateField("role", e.target.value)}
                >
                  <option value="AUTHOR">{cms("STATUS_LABELS.role.author", "Author")}</option>
                  <option value="REVIEWER">{cms("STATUS_LABELS.role.reviewer", "Reviewer")}</option>
                  <option value="ADMIN">{cms("STATUS_LABELS.role.admin", "Admin")}</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.designation", "Designation")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.designation}
                  onChange={(e) => updateField("designation", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.institution", "Institution")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.institution}
                  onChange={(e) => updateField("institution", e.target.value)}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {cms("ADMIN_USERS.users_modal.department", "Department")}
                </label>
                <input
                  className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
                  value={form.department}
                  onChange={(e) => updateField("department", e.target.value)}
                />
              </div>
            </div>

            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => {
                  setEditUser(null);
                  setForm(emptyForm);
                }}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={handleSubmitEdit}
                disabled={!form.nameHi || !form.nameEn || !form.email || updateMutation.isPending}
                className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 disabled:opacity-50 transition"
              >
                {updateMutation.isPending ? "..." : cms("ADMIN_USERS.users_modal.update_btn", "Update")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Delete Confirmation Modal ─── */}
      {deleteConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-sm bg-white rounded-xl shadow-xl p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              {cms("ADMIN_USERS.users_modal.delete_title", "Delete User")}
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              {cms("ADMIN_USERS.users_modal.delete_confirm_pre", "Are you sure you want to delete")}{" "}
              <strong>{displayName(deleteConfirm)}</strong> ({deleteConfirm.email})?{" "}
              {cms("ADMIN_USERS.users_modal.delete_confirm_post", "This action cannot be undone.")}
            </p>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setDeleteConfirm(null)}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={() => deleteMutation.mutate(deleteConfirm.id)}
                disabled={deleteMutation.isPending}
                className="rounded-md bg-red-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-red-700 disabled:opacity-50 transition"
              >
                {deleteMutation.isPending ? "..." : cms("ADMIN_USERS.users_modal.delete_btn", "Delete")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Temporary Password Modal ─── */}
      {createdUserInfo && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-md bg-white rounded-xl shadow-xl p-6">
            <h3 className="text-lg font-semibold text-green-700 mb-3">
              {cms("ADMIN_USERS.users_modal.user_created_title", "User Created Successfully")}
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              {cms("ADMIN_USERS.users_modal.temp_password_info", "Please share the temporary password with the user. They will be required to change it on first login.")}
            </p>
            <div className="rounded-lg bg-gray-50 border border-gray-200 p-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">{cms("ADMIN_USERS.users_modal.name_en", "Name (English)")}</span>
                <span className="font-medium text-gray-900">{createdUserInfo.nameEn}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-500">{cms("ADMIN_USERS.users_modal.email", "Email")}</span>
                <span className="font-medium text-gray-900">{createdUserInfo.email}</span>
              </div>
              <div className="flex justify-between items-center text-sm pt-2 border-t border-gray-200">
                <span className="text-gray-500">{cms("ADMIN_USERS.users_modal.temp_password_label", "Temporary Password")}</span>
                <span className="font-mono font-bold text-lg text-indigo-700 tracking-wide select-all">
                  {createdUserInfo.temporaryPassword}
                </span>
              </div>
            </div>
            <div className="flex justify-end mt-6">
              <button
                onClick={() => setCreatedUserInfo(null)}
                className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition"
              >
                {cms("COMMON.buttons.done", "Done")}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
