"use client"

import { useState, useEffect } from "react"
import {
  Users,
  Search,
  UserCheck,
  UserPlus,
  ShieldCheck,
  Ban,
  Trash2,
  Mail,
  Phone,
  Loader2,
  Key,
  X,
  Save,
  Star,
  Plus,
  Minus,
  Hash,
} from "lucide-react"
import api from "@/lib/axios"
import Swal from "sweetalert2";

export default function UsersPage() {
  const [search, setSearch] = useState("")
  const [roleFilter, setRoleFilter] = useState<string>("ALL")

  const [users, setUsers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalRecords, setTotalRecords] = useState(0)

  async function fetchUsers() {
    try {
      setLoading(true)
      const res = await api.get(`/admin/users?page=${page}&limit=20&search=${search}&role=${roleFilter}`)
      setUsers(res.data.data || res.data)
      if (res.data.meta) {
        setTotalPages(res.data.meta.totalPages)
        setTotalRecords(res.data.meta.total)
      }
    } catch (error) {
      console.error("Failed to fetch users", error)
    } finally {
      setLoading(false)
    }
  }

  // Debounced fetch
  useEffect(() => {
    const handler = setTimeout(() => {
      fetchUsers()
    }, 500)
    return () => clearTimeout(handler)
  }, [page, search, roleFilter])

  // Reset page to 1 when search or filter changes
  useEffect(() => {
    setPage(1)
  }, [search, roleFilter])

  // Modal States
  const [isAddModalOpen, setIsAddModalOpen] = useState(false)
  const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false)
  const [isRewardModalOpen, setIsRewardModalOpen] = useState(false)
  const [selectedUserId, setSelectedUserId] = useState("")
  const [selectedUser, setSelectedUser] = useState<any>(null)

  const [newUser, setNewUser] = useState({ name: "", email: "", phone: "", role: "USER", password: "" })
  const [newPassword, setNewPassword] = useState("")
  const [submitting, setSubmitting] = useState(false)

  // Reward points state
  const [rewardOperation, setRewardOperation] = useState<"add" | "deduct" | "set">("add")
  const [rewardAmount, setRewardAmount] = useState("")
  const [rewardSubmitting, setRewardSubmitting] = useState(false)

  async function handleCreateUser(e: React.FormEvent) {
    e.preventDefault()
    if (!newUser.name || !newUser.email || !newUser.password) {
      Swal.fire({ text: "Name, email, and password are required", confirmButtonColor: "#18181b" })
      return
    }

    try {
      setSubmitting(true)
      await api.post("/admin/users", newUser)
      setIsAddModalOpen(false)
      setNewUser({ name: "", email: "", phone: "", role: "USER", password: "" })
      await fetchUsers()
    } catch (error: any) {
      console.error(error)
      Swal.fire({ text: error.response?.data?.message || "Failed to create user", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSubmitting(false)
    }
  }

  async function handleChangePassword(e: React.FormEvent) {
    e.preventDefault()
    if (!newPassword) return

    try {
      setSubmitting(true)
      await api.put(`/admin/users/${selectedUserId}/password`, { password: newPassword })
      setIsPasswordModalOpen(false)
      setNewPassword("")
      Swal.fire({ text: "Password updated successfully!", confirmButtonColor: "#18181b", icon: "success" })
    } catch (error) {
      console.error(error)
      Swal.fire({ text: "Failed to update password", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSubmitting(false)
    }
  }

  async function handleRewardPoints(e: React.FormEvent) {
    e.preventDefault()
    const amount = parseInt(rewardAmount)
    if (!rewardAmount || isNaN(amount) || amount < 0) {
      Swal.fire({ text: "Please enter a valid amount.", confirmButtonColor: "#18181b" })
      return
    }

    try {
      setRewardSubmitting(true)
      const res = await api.patch(`/admin/users/${selectedUser.id}/reward-points`, {
        operation: rewardOperation,
        amount,
      })
      // Update user in list optimistically
      setUsers((prev) =>
        prev.map((u) =>
          u.id === selectedUser.id ? { ...u, rewardPoints: res.data.rewardPoints } : u
        )
      )
      setSelectedUser((prev: any) => ({ ...prev, rewardPoints: res.data.rewardPoints }))
      setRewardAmount("")
      Swal.fire({ text: `Reward points updated successfully! New balance: ${res.data.rewardPoints} pts`, confirmButtonColor: "#18181b", icon: "success" })
      setIsRewardModalOpen(false)
    } catch (error: any) {
      console.error(error)
      Swal.fire({ text: error.response?.data?.message || "Failed to update reward points", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setRewardSubmitting(false)
    }
  }

  // Filter logic handled by server

  // Role switching handler
  async function handleRoleChange(id: string, newRole: string) {
    setUsers((prev) => prev.map((u) => (u.id === id ? { ...u, role: newRole } : u)))
    try {
      await api.put(`/admin/users/${id}`, { role: newRole })
    } catch (error) {
      console.error("Failed to update user role", error)
      Swal.fire({ text: "Failed to update role.", confirmButtonColor: "#18181b", icon: "error" })
      fetchUsers()
    }
  }

  // Delete handler
  async function handleDeleteUser(id: string) {
    if (!(await Swal.fire({ title: "Are you sure?", text: "Are you sure you want to remove this client profile from active records?", icon: "warning", showCancelButton: true, confirmButtonColor: "#18181b", cancelButtonColor: "#ef4444", confirmButtonText: "Yes" })).isConfirmed) return

    setUsers((prev) => prev.filter((u) => u.id !== id))
    try {
      await api.delete(`/admin/users/${id}`)
    } catch (error) {
      console.error("Failed to delete user", error)
      Swal.fire({ text: "Failed to delete user.", confirmButtonColor: "#18181b", icon: "error" })
      fetchUsers()
    }
  }

  // Aggregate stats
  const totalClients = users.length
  const adminCount = users.filter((u) => u.role === "ADMIN").length
  const customerCount = users.filter((u) => u.role === "USER").length
  const totalRewardPoints = users.reduce((sum, u) => sum + (u.rewardPoints || 0), 0)

  return (
    <div className="space-y-5 max-w-7xl mx-auto p-2 overflow-x-hidden">
      {/* HEADER */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <div className="p-3 bg-zinc-900 text-white rounded-2xl shadow-xl">
              <Users size={24} />
            </div>
            <h1 className="text-2xl font-extrabold tracking-tight text-zinc-900">
              User Profiles
            </h1>
          </div>
          <p className="text-zinc-500 mt-2 text-sm max-w-md">
            Supervise client credentials, admin roles, reward points, and active permissions across the fashion house.
          </p>
        </div>

        {/* TOP LEVEL ACTION */}
        <button
          onClick={() => setIsAddModalOpen(true)}
          className="flex items-center gap-2 px-5 py-2.5 bg-zinc-950 hover:bg-zinc-800 text-white font-semibold rounded-2xl transition cursor-pointer shadow-xl text-sm shrink-0"
        >
          <UserPlus className="w-4 h-4" />
          Invite Associate
        </button>
      </div>

      {/* METRICS ROW */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {/* Total Users */}
        <div className="bg-white border border-zinc-100 rounded-3xl p-4 shadow-sm flex items-center gap-4">
          <div className="p-3 bg-indigo-50 text-indigo-600 rounded-2xl">
            <Users className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-semibold text-zinc-400 uppercase tracking-widest">Total Accounts</p>
            <h4 className="text-xl font-black text-zinc-950 font-mono">{totalClients}</h4>
          </div>
        </div>

        {/* Admins */}
        <div className="bg-white border border-zinc-100 rounded-3xl p-4 shadow-sm flex items-center gap-4">
          <div className="p-3 bg-emerald-50 text-emerald-600 rounded-2xl">
            <ShieldCheck className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-semibold text-zinc-400 uppercase tracking-widest">Administrators</p>
            <h4 className="text-xl font-black text-zinc-950 font-mono">{adminCount}</h4>
          </div>
        </div>

        {/* Customers */}
        <div className="bg-white border border-zinc-100 rounded-3xl p-4 shadow-sm flex items-center gap-4">
          <div className="p-3 bg-violet-50 text-violet-600 rounded-2xl">
            <UserCheck className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-semibold text-zinc-400 uppercase tracking-widest">Curated Clientele</p>
            <h4 className="text-xl font-black text-zinc-950 font-mono">{customerCount}</h4>
          </div>
        </div>

        {/* Total Reward Points */}
        <div className="bg-white border border-zinc-100 rounded-3xl p-4 shadow-sm flex items-center gap-4">
          <div className="p-3 bg-amber-50 text-amber-500 rounded-2xl">
            <Star className="w-5 h-5" />
          </div>
          <div>
            <p className="text-[10px] font-semibold text-zinc-400 uppercase tracking-widest">Total Reward Pts</p>
            <h4 className="text-xl font-black text-zinc-950 font-mono">{totalRewardPoints.toLocaleString()}</h4>
          </div>
        </div>
      </div>

      {/* FILTER & SEARCH PANEL */}
      <div className="bg-white rounded-3xl border border-zinc-100 p-6 shadow-sm">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          {/* SEARCH */}
          <div className="relative flex-1">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 w-5 h-5" />
            <input
              type="text"
              placeholder="Search user profile names, email addresses..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full border border-zinc-200 rounded-2xl pl-12 pr-5 py-4 focus:outline-none focus:ring-2 focus:ring-zinc-950 focus:border-transparent transition bg-zinc-50/50 text-sm"
            />
          </div>

          {/* FILTER DROPDOWN */}
          <div className="flex gap-3">
            <select
              value={roleFilter}
              onChange={(e) => setRoleFilter(e.target.value)}
              className="border border-zinc-200 rounded-2xl px-5 py-4 bg-zinc-50/50 text-sm focus:outline-none focus:ring-2 focus:ring-zinc-950 text-zinc-600 font-medium"
            >
              <option value="ALL">All Member Roles</option>
              <option value="ADMIN">Administrators</option>
              <option value="USER">Standard Customers</option>
            </select>
          </div>
        </div>

        {/* MEMBERS DATABASE TABLE */}
        <div className="mt-8 overflow-x-auto rounded-2xl border border-zinc-100 w-full">
          <table className="w-full border-collapse text-left bg-white" style={{ minWidth: '900px' }}>
            <thead>
              <tr className="bg-zinc-50/80 border-b border-zinc-100 text-zinc-400 text-[10px] font-bold uppercase tracking-widest">
                <th className="py-5 px-6">Curated Client / Email</th>
                <th className="py-5 px-6">Phone Number</th>
                <th className="py-5 px-6">System Role</th>
                <th className="py-5 px-6">
                  <span className="flex items-center gap-1.5">
                    <Star className="w-3.5 h-3.5 text-amber-400" />
                    Reward Points
                  </span>
                </th>
                <th className="py-5 px-6">Joined Date</th>
                <th className="py-5 px-6 text-center">Control Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {loading ? (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Loader2 className="w-8 h-8 animate-spin text-zinc-300 mx-auto mb-3" />
                    <p className="text-xs text-zinc-400 font-bold uppercase tracking-widest">Syncing Users...</p>
                  </td>
                </tr>
              ) : users.length === 0 ? (
                <tr>
                  <td colSpan={7} className="text-center py-24 text-zinc-400 text-xs font-bold uppercase tracking-widest">
                    No users found matching your criteria.
                  </td>
                </tr>
              ) : (
                users.map((user) => (
                  <tr key={user.id} className="hover:bg-zinc-50/50 transition duration-150 group">
                    {/* CLIENT EMAIL */}
                    <td className="py-5 px-6">
                      <div className="flex items-center gap-4">
                        <div className="w-11 h-11 rounded-full bg-zinc-900 text-white font-extrabold text-xs flex items-center justify-center border shadow-sm">
                          {user.name ? user.name.charAt(0).toUpperCase() : "?"}
                        </div>
                        <div>
                          <h5 className="font-bold text-zinc-950 text-sm group-hover:text-indigo-600 transition">
                            {user.name}
                          </h5>
                          <p className="text-xs text-zinc-400 flex items-center gap-1 mt-0.5">
                            <Mail className="w-3 h-3" />
                            {user.email}
                          </p>
                        </div>
                      </div>
                    </td>

                    {/* PHONE */}
                    <td className="py-5 px-6 font-mono text-xs font-semibold text-zinc-500">
                      <div className="flex items-center gap-1.5">
                        <Phone className="w-3.5 h-3.5 text-zinc-400" />
                        {user.phone || "N/A"}
                      </div>
                    </td>

                    {/* ROLE */}
                    <td className="py-5 px-6">
                      <select
                        value={user.role}
                        onChange={(e) => handleRoleChange(user.id, e.target.value)}
                        className="border border-zinc-200 rounded-xl px-3 py-1.5 text-xs bg-white focus:outline-none focus:ring-1 focus:ring-zinc-950 text-zinc-800 font-semibold cursor-pointer"
                      >
                        <option value="ADMIN">ADMIN</option>
                        <option value="USER">USER</option>
                      </select>
                    </td>

                    {/* REWARD POINTS */}
                    <td className="py-5 px-6">
                      <div className="flex items-center gap-2">
                        <span
                          className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-black font-mono border ${
                            (user.rewardPoints || 0) > 0
                              ? "bg-amber-50 text-amber-700 border-amber-200"
                              : "bg-zinc-50 text-zinc-400 border-zinc-200"
                          }`}
                        >
                          <Star className="w-3 h-3" />
                          {(user.rewardPoints || 0).toLocaleString()}
                        </span>
                        <button
                          onClick={() => {
                            setSelectedUser(user)
                            setRewardOperation("add")
                            setRewardAmount("")
                            setIsRewardModalOpen(true)
                          }}
                          className="p-1.5 rounded-lg border border-transparent hover:border-amber-200 text-zinc-400 hover:text-amber-600 hover:bg-amber-50/60 transition cursor-pointer"
                          title="Manage Reward Points"
                        >
                          <Star size={13} />
                        </button>
                      </div>
                    </td>

                    {/* JOINED */}
                    <td className="py-5 px-6 text-xs font-bold text-zinc-400 font-mono">
                      {new Date(user.createdAt).toLocaleDateString()}
                    </td>

                    {/* ACTIONS */}
                    <td className="py-5 px-6 text-center">
                      <div className="flex items-center justify-center gap-1.5">
                        <button
                          onClick={() => {
                            setSelectedUserId(user.id)
                            setIsPasswordModalOpen(true)
                          }}
                          className="p-2.5 rounded-xl border border-transparent hover:border-indigo-100 text-zinc-400 hover:text-indigo-600 hover:bg-indigo-50/50 transition cursor-pointer"
                          title="Change Password"
                        >
                          <Key size={15} />
                        </button>
                        <button
                          onClick={() => handleDeleteUser(user.id)}
                          className="p-2.5 rounded-xl border border-transparent hover:border-red-100 text-zinc-400 hover:text-red-500 hover:bg-red-50/50 transition cursor-pointer"
                          title="Delete Member"
                        >
                          <Trash2 size={15} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* PAGINATION */}
        {totalPages > 1 && (
          <div className="flex justify-between items-center mt-6">
            <span className="text-xs text-zinc-500 font-medium">
              Showing page {page} of {totalPages} ({totalRecords} total)
            </span>
            <div className="flex gap-2">
              <button
                disabled={page === 1}
                onClick={() => setPage(p => p - 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-zinc-50 disabled:opacity-50 transition cursor-pointer"
              >
                Previous
              </button>
              <button
                disabled={page === totalPages}
                onClick={() => setPage(p => p + 1)}
                className="px-4 py-2 border border-zinc-200 rounded-xl text-xs font-bold hover:bg-zinc-50 disabled:opacity-50 transition cursor-pointer"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>

      {/* ─── REWARD POINTS MODAL ─── */}
      {isRewardModalOpen && selectedUser && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/60 backdrop-blur-sm">
          <div className="bg-white rounded-3xl w-full max-w-md shadow-2xl overflow-hidden border border-zinc-200/50">
            {/* Header */}
            <div className="p-6 border-b border-zinc-100 flex items-center justify-between bg-gradient-to-r from-amber-50 to-yellow-50">
              <div className="flex items-center gap-3">
                <div className="p-2.5 bg-amber-100 text-amber-600 rounded-xl">
                  <Star className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-base font-black text-zinc-900">Manage Reward Points</h2>
                  <p className="text-[11px] text-zinc-500 font-medium mt-0.5">{selectedUser.name} · {selectedUser.email}</p>
                </div>
              </div>
              <button
                onClick={() => setIsRewardModalOpen(false)}
                className="w-8 h-8 rounded-full bg-white border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-zinc-900 transition shadow-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Current Balance */}
            <div className="px-6 pt-5">
              <div className="flex items-center justify-between bg-zinc-50 border border-zinc-100 rounded-2xl p-4">
                <span className="text-xs font-bold uppercase tracking-widest text-zinc-500">Current Balance</span>
                <span className="text-2xl font-black text-amber-600 font-mono flex items-center gap-1.5">
                  <Star className="w-5 h-5" />
                  {(selectedUser.rewardPoints || 0).toLocaleString()}
                  <span className="text-xs font-normal text-zinc-400 ml-1">pts</span>
                </span>
              </div>
            </div>

            <form onSubmit={handleRewardPoints} className="p-6 space-y-5">
              {/* Operation Type */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2.5">
                  Operation Type
                </label>
                <div className="grid grid-cols-3 gap-2">
                  {[
                    { value: "add", label: "Add", icon: Plus, color: "emerald" },
                    { value: "deduct", label: "Deduct", icon: Minus, color: "rose" },
                    { value: "set", label: "Set", icon: Hash, color: "indigo" },
                  ].map((op) => {
                    const Icon = op.icon
                    const isActive = rewardOperation === op.value
                    const colorMap: Record<string, string> = {
                      emerald: isActive
                        ? "bg-emerald-600 border-emerald-600 text-white"
                        : "border-zinc-200 text-zinc-500 hover:border-emerald-300 hover:text-emerald-600",
                      rose: isActive
                        ? "bg-rose-600 border-rose-600 text-white"
                        : "border-zinc-200 text-zinc-500 hover:border-rose-300 hover:text-rose-600",
                      indigo: isActive
                        ? "bg-indigo-600 border-indigo-600 text-white"
                        : "border-zinc-200 text-zinc-500 hover:border-indigo-300 hover:text-indigo-600",
                    }
                    return (
                      <button
                        key={op.value}
                        type="button"
                        onClick={() => setRewardOperation(op.value as "add" | "deduct" | "set")}
                        className={`flex flex-col items-center gap-1.5 py-3 px-2 rounded-xl border-2 text-[10px] font-black uppercase tracking-widest transition-all cursor-pointer ${colorMap[op.color]}`}
                      >
                        <Icon className="w-4 h-4" />
                        {op.label}
                      </button>
                    )
                  })}
                </div>
                <p className="text-[10px] text-zinc-400 mt-2 font-medium">
                  {rewardOperation === "add" && "➕ Adds points to current balance."}
                  {rewardOperation === "deduct" && "➖ Deducts points from balance (min 0)."}
                  {rewardOperation === "set" && "🔢 Replaces current balance with the entered value."}
                </p>
              </div>

              {/* Amount Input */}
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">
                  Points Amount *
                </label>
                <div className="relative">
                  <Star className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-amber-400" />
                  <input
                    type="number"
                    min="0"
                    required
                    value={rewardAmount}
                    onChange={(e) => setRewardAmount(e.target.value)}
                    className="w-full border border-zinc-200 rounded-xl pl-10 pr-5 py-3 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-amber-400 focus:border-transparent transition font-mono font-bold"
                    placeholder="Enter points..."
                  />
                </div>

                {/* Preview */}
                {rewardAmount && !isNaN(parseInt(rewardAmount)) && (
                  <div className="mt-2 text-[11px] font-semibold text-zinc-500 flex items-center gap-1">
                    Preview: &nbsp;
                    <span className="font-black text-zinc-800">
                      {rewardOperation === "add" &&
                        `${(selectedUser.rewardPoints || 0).toLocaleString()} + ${parseInt(rewardAmount).toLocaleString()} = `}
                      {rewardOperation === "deduct" &&
                        `${(selectedUser.rewardPoints || 0).toLocaleString()} − ${parseInt(rewardAmount).toLocaleString()} = `}
                      {rewardOperation === "set" && "New balance = "}
                    </span>
                    <span className="font-black text-amber-600 font-mono">
                      {rewardOperation === "add" &&
                        ((selectedUser.rewardPoints || 0) + parseInt(rewardAmount)).toLocaleString()}
                      {rewardOperation === "deduct" &&
                        Math.max(0, (selectedUser.rewardPoints || 0) - parseInt(rewardAmount)).toLocaleString()}
                      {rewardOperation === "set" && parseInt(rewardAmount).toLocaleString()}
                      {" pts"}
                    </span>
                  </div>
                )}
              </div>

              {/* Buttons */}
              <div className="pt-2 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsRewardModalOpen(false)}
                  className="px-5 py-2.5 rounded-xl border border-zinc-200 text-zinc-600 font-bold text-xs uppercase tracking-widest hover:bg-zinc-50 transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={rewardSubmitting}
                  className="px-6 py-2.5 rounded-xl bg-amber-500 hover:bg-amber-600 text-white font-black text-xs uppercase tracking-widest transition shadow-lg flex items-center gap-2 disabled:opacity-50"
                >
                  {rewardSubmitting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  Apply Points
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ADD USER MODAL */}
      {isAddModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/60 backdrop-blur-sm">
          <div className="bg-white rounded-3xl w-full max-w-md shadow-2xl overflow-hidden border border-zinc-200/50">
            <div className="p-6 border-b border-zinc-100 flex items-center justify-between bg-zinc-50/50">
              <h2 className="text-xl font-black text-zinc-900">Add New User</h2>
              <button
                onClick={() => setIsAddModalOpen(false)}
                className="w-8 h-8 rounded-full bg-white border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-zinc-900 transition shadow-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleCreateUser} className="p-6 space-y-4">
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Full Name *</label>
                <input
                  type="text"
                  required
                  value={newUser.name}
                  onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                  placeholder="E.g. Jane Doe"
                />
              </div>

              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Email Address *</label>
                <input
                  type="email"
                  required
                  value={newUser.email}
                  onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                  placeholder="jane@example.com"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Phone</label>
                  <input
                    type="text"
                    value={newUser.phone}
                    onChange={(e) => setNewUser({ ...newUser, phone: e.target.value })}
                    className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                    placeholder="+1 555-0199"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Role</label>
                  <select
                    value={newUser.role}
                    onChange={(e) => setNewUser({ ...newUser, role: e.target.value })}
                    className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition cursor-pointer"
                  >
                    <option value="USER">USER</option>
                    <option value="ADMIN">ADMIN</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">Initial Password *</label>
                <input
                  type="password"
                  required
                  value={newUser.password}
                  onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                  placeholder="••••••••"
                />
              </div>

              <div className="pt-4 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsAddModalOpen(false)}
                  className="px-5 py-2.5 rounded-xl border border-zinc-200 text-zinc-600 font-bold text-xs uppercase tracking-widest hover:bg-zinc-50 transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="px-6 py-2.5 rounded-xl bg-zinc-950 hover:bg-zinc-800 text-white font-black text-xs uppercase tracking-widest transition shadow-lg flex items-center gap-2 disabled:opacity-50"
                >
                  {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                  Create User
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* CHANGE PASSWORD MODAL */}
      {isPasswordModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-zinc-950/60 backdrop-blur-sm">
          <div className="bg-white rounded-3xl w-full max-w-sm shadow-2xl overflow-hidden border border-zinc-200/50">
            <div className="p-6 border-b border-zinc-100 flex items-center justify-between bg-zinc-50/50">
              <h2 className="text-xl font-black text-zinc-900">Change Password</h2>
              <button
                onClick={() => setIsPasswordModalOpen(false)}
                className="w-8 h-8 rounded-full bg-white border border-zinc-200 flex items-center justify-center text-zinc-400 hover:text-zinc-900 transition shadow-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <form onSubmit={handleChangePassword} className="p-6 space-y-4">
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-zinc-500 mb-2">New Password *</label>
                <input
                  type="password"
                  required
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  className="w-full border border-zinc-200 rounded-xl px-4 py-2.5 text-sm bg-zinc-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-zinc-950 transition"
                  placeholder="••••••••"
                />
              </div>

              <div className="pt-4 flex items-center justify-end gap-3">
                <button
                  type="button"
                  onClick={() => setIsPasswordModalOpen(false)}
                  className="px-5 py-2.5 rounded-xl border border-zinc-200 text-zinc-600 font-bold text-xs uppercase tracking-widest hover:bg-zinc-50 transition"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={submitting}
                  className="px-6 py-2.5 rounded-xl bg-zinc-950 hover:bg-zinc-800 text-white font-black text-xs uppercase tracking-widest transition shadow-lg flex items-center gap-2 disabled:opacity-50"
                >
                  {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                  Update
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
