'use client'

import { useEffect, useMemo, useState } from "react"
import {
  Ban,
  KeyRound,
  LogOut,
  PlusCircle,
  RefreshCw,
  ShieldCheck,
  ShieldX,
  Trash2,
  UserCog,
  Users,
} from "lucide-react"
import { toast } from "sonner"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { KpiCard } from "@/components/ui/kpi-card"
import { DataTable, type Column } from "@/components/ui/data-table"
import { FilterToolbar } from "@/components/ui/filter-toolbar"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Modal } from "@/components/ui/modal"
import { Button } from "@/components/ui/button"
import { InputField, SelectField, TextAreaField } from "@/components/ui/FormFields"
import { formatDateTime } from "@/lib/format"
import { useAuth } from "@/contexts/auth-context"
import { useUsers } from "@/hooks/useUsers"
import { hasPermission, isSuperAdminUser } from "@/lib/permissions"
import type {
  AdminRoleRead,
  AdminUserRead,
  IpBlacklistCreatePayload,
  IpBlacklistRead,
  UserCreatePayload,
  UserUpdatePayload,
} from "@/types"

const statusTone: Record<string, StatusTone> = {
  active: "success",
  pending: "pending",
  suspended: "warning",
  inactive: "neutral",
  blocked: "danger",
  archived: "neutral",
}

const initialCreateForm: UserCreatePayload = {
  email: "",
  phone: "",
  full_name_ar: "",
  role_ids: [],
  auto_approve: false,
  password: "",
}

type EditForm = UserUpdatePayload & { role_ids: string[] }

function displayUser(user: Pick<AdminUserRead, "email" | "phone" | "id"> & { full_name_ar?: string | null; full_name_en?: string | null }) {
  return user.full_name_ar || user.full_name_en || user.email || user.phone || user.id.slice(0, 8)
}

function roleName(role: AdminRoleRead) {
  return role.name_ar || role.name_en || role.code
}

function isLikelyIp(value: string) {
  const ip = value.trim()
  const ipv4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
  const ipv6 = /^[0-9a-f:]+$/i
  return ipv4.test(ip) || (ip.includes(":") && ipv6.test(ip))
}

function generateTemporaryPassword() {
  const lower = "abcdefghijklmnopqrstuvwxyz"
  const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  const digits = "0123456789"
  const special = "!@#$%^&*"
  const all = lower + upper + digits + special
  const pick = (chars: string) => chars[secureRandom(chars.length)]
  const chars = [pick(lower), pick(upper), pick(digits), pick(special)]

  while (chars.length < 16) {
    chars.push(pick(all))
  }

  for (let i = chars.length - 1; i > 0; i -= 1) {
    const j = secureRandom(i + 1)
    ;[chars[i], chars[j]] = [chars[j], chars[i]]
  }

  return chars.join("")
}

function secureRandom(max: number) {
  if (typeof window !== "undefined" && window.crypto?.getRandomValues) {
    const value = new Uint32Array(1)
    window.crypto.getRandomValues(value)
    return value[0] % max
  }
  return Math.floor(Math.random() * max)
}

export default function UsersPage() {
  const {
    users,
    pendingApprovals,
    roles,
    blacklistEntries,
    selectedUser,
    selectedUserRoles,
    whitelistIps,
    isLoading,
    isSubmitting,
    error,
    fetchUsers,
    fetchPendingApprovals,
    fetchRoles,
    fetchBlacklistEntries,
    fetchUserDetail,
    createUser,
    updateUser,
    approveAdmin,
    regeneratePassword,
    revokeSessions,
    deleteUser,
    fetchWhitelistIps,
    replaceWhitelistIps,
    createBlacklistEntry,
    expireBlacklistEntry,
    setSelectedUser,
  } = useUsers()
  const { user: authUser, isLoading: isAuthLoading } = useAuth()

  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("")
  const [typeFilter, setTypeFilter] = useState("")
  const [createOpen, setCreateOpen] = useState(false)
  const [editOpen, setEditOpen] = useState(false)
  const [passwordOpen, setPasswordOpen] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [allowlistOpen, setAllowlistOpen] = useState(false)
  const [allowlistConfirmOpen, setAllowlistConfirmOpen] = useState(false)
  const [blacklistOpen, setBlacklistOpen] = useState(false)
  const [blacklistConfirmOpen, setBlacklistConfirmOpen] = useState(false)
  const [unblockOpen, setUnblockOpen] = useState(false)
  const [selectedBlacklistEntry, setSelectedBlacklistEntry] = useState<IpBlacklistRead | null>(null)
  const [createForm, setCreateForm] = useState<UserCreatePayload>(initialCreateForm)
  const [editForm, setEditForm] = useState<EditForm>({ email: "", phone: "", full_name_ar: "", status: "active", role_ids: [] })
  const [allowlistText, setAllowlistText] = useState("")
  const [pendingAllowlistIps, setPendingAllowlistIps] = useState<string[]>([])
  const [blacklistForm, setBlacklistForm] = useState({ ip_address: "", reason: "", expires_at: "" })
  const [pendingBlacklistEntry, setPendingBlacklistEntry] = useState<IpBlacklistCreatePayload | null>(null)
  const [unblockReason, setUnblockReason] = useState("")
  const [generatedPassword, setGeneratedPassword] = useState("")

  useEffect(() => {
    fetchUsers()
    fetchPendingApprovals()
    fetchRoles()
    fetchBlacklistEntries()
  }, [fetchBlacklistEntries, fetchPendingApprovals, fetchRoles, fetchUsers])

  const filteredUsers = useMemo(() => {
    return users.filter((user) => {
      const matchesStatus = !statusFilter || user.status === statusFilter
      const matchesType = !typeFilter || user.user_type === typeFilter
      return matchesStatus && matchesType
    })
  }, [statusFilter, typeFilter, users])

  const adminUsers = users.filter((user) => ["admin", "employee"].includes(user.user_type)).length
  const approvedAdmins = users.filter((user) => user.is_admin_approved).length
  const passwordResetRequired = users.filter((user) => user.must_change_password).length
  const activeBlacklistCount = blacklistEntries.filter((entry) => entry.is_active).length
  const isSuperAdmin = isSuperAdminUser(authUser)
  const canCreateUser = hasPermission(authUser, "users:create")
  const canUpdateUser = hasPermission(authUser, "users:update")
  const canApproveUser = hasPermission(authUser, "users:approve")
  const canResetPassword = hasPermission(authUser, "users:reset_password")
  const canDisableUser = hasPermission(authUser, "users:disable")
  const canManageIp = hasPermission(authUser, "users:manage_ip")
  const canManageSessions = hasPermission(authUser, "users:manage_sessions")
  const canAssignRoles = hasPermission(authUser, "roles:assign_users")
  const protectedActionDisabled = isAuthLoading || !isSuperAdmin

  const requireCapability = (allowed: boolean) => {
    if (allowed) return true
    toast.error("You do not have permission to perform this action.")
    return false
  }

  const openUser = async (user: AdminUserRead) => {
    setSelectedUser(user)
    await fetchUserDetail(user.id)
  }

  const openEdit = async (user: AdminUserRead) => {
    if (!requireCapability(canUpdateUser)) return
    const detail = await fetchUserDetail(user.id)
    setEditForm({
      email: user.email ?? "",
      phone: user.phone ?? "",
      full_name_ar: detail?.user?.full_name_ar ?? user.full_name_ar ?? "",
      status: user.status,
      role_ids: detail?.roles.map((role) => role.id) ?? [],
    })
    setEditOpen(true)
  }

  const openAllowlist = async (user: AdminUserRead) => {
    if (!requireCapability(canManageIp)) return
    setSelectedUser(user)
    const ips = await fetchWhitelistIps(user.id)
    setAllowlistText(ips.join("\n"))
    setAllowlistOpen(true)
  }

  const submitCreate = async () => {
    if (!requireCapability(canCreateUser)) return
    if (!createForm.email && !createForm.phone) {
      toast.error("Email or phone is required.")
      return
    }
    const result = await createUser({
      ...createForm,
      email: createForm.email || null,
      phone: createForm.phone || null,
      full_name_ar: createForm.full_name_ar || null,
      password: createForm.password || null,
    })
    if (!result) return
    toast.success("User created.")
    if (result.temp_password) setGeneratedPassword(result.temp_password)
    setCreateForm(initialCreateForm)
    setCreateOpen(false)
    setPasswordOpen(Boolean(result.temp_password))
  }

  const submitEdit = async () => {
    if (!selectedUser) return
    if (!requireCapability(canUpdateUser)) return
    const ok = await updateUser(
      selectedUser.id,
      {
        email: editForm.email || null,
        phone: editForm.phone || null,
        full_name_ar: editForm.full_name_ar || null,
        status: editForm.status,
      },
      canAssignRoles ? editForm.role_ids : undefined,
    )
    if (ok) {
      toast.success("User updated.")
      setEditOpen(false)
    }
  }

  const submitAllowlist = async () => {
    if (!selectedUser) return
    if (!requireCapability(canManageIp)) return
    const ips = allowlistText
      .split(/\r?\n|,/)
      .map((ip) => ip.trim())
      .filter(Boolean)
    const invalid = ips.find((ip) => !isLikelyIp(ip))
    if (invalid) {
      toast.error(`Invalid IP address: ${invalid}`)
      return
    }
    setPendingAllowlistIps(Array.from(new Set(ips)))
    setAllowlistConfirmOpen(true)
  }

  const confirmAllowlistSave = async () => {
    if (!selectedUser) return
    if (!requireCapability(canManageIp)) return
    const ok = await replaceWhitelistIps(selectedUser.id, pendingAllowlistIps)
    if (ok) {
      toast.success("IP allowlist updated.")
      setPendingAllowlistIps([])
      setAllowlistConfirmOpen(false)
      setAllowlistOpen(false)
    }
  }

  const submitBlacklist = async () => {
    if (!requireCapability(isSuperAdmin)) return
    const ip = blacklistForm.ip_address.trim()
    if (!isLikelyIp(ip)) {
      toast.error("Enter a valid IPv4 or IPv6 address.")
      return
    }
    if (!blacklistForm.reason.trim()) {
      toast.error("Reason is required.")
      return
    }
    setPendingBlacklistEntry({
      ip_address: ip,
      reason: blacklistForm.reason.trim(),
      expires_at: blacklistForm.expires_at || null,
    })
    setBlacklistConfirmOpen(true)
  }

  const confirmBlacklistCreate = async () => {
    if (!pendingBlacklistEntry) return
    if (!requireCapability(isSuperAdmin)) return
    const ok = await createBlacklistEntry(pendingBlacklistEntry)
    if (ok) {
      toast.success("IP address blocked.")
      setBlacklistForm({ ip_address: "", reason: "", expires_at: "" })
      setPendingBlacklistEntry(null)
      setBlacklistConfirmOpen(false)
      setBlacklistOpen(false)
    }
  }

  const submitUnblock = async () => {
    if (!selectedBlacklistEntry) return
    if (!requireCapability(isSuperAdmin)) return
    const ok = await expireBlacklistEntry(selectedBlacklistEntry.id, unblockReason)
    if (ok) {
      toast.success("IP address unblocked.")
      setUnblockReason("")
      setSelectedBlacklistEntry(null)
      setUnblockOpen(false)
    }
  }

  const submitRegeneratePassword = async () => {
    if (!selectedUser) return
    if (!requireCapability(canResetPassword)) return
    const result = await regeneratePassword(selectedUser.id)
    if (result?.temp_password) {
      setGeneratedPassword(result.temp_password)
      toast.success("Temporary password regenerated.")
    }
  }

  const submitRevokeSessions = async () => {
    if (!selectedUser || !requireCapability(canManageSessions)) return
    const ok = await revokeSessions(selectedUser.id)
    if (ok) toast.success("All active sessions were revoked.")
  }

  const submitDelete = async () => {
    if (!selectedUser) return
    if (!requireCapability(canDisableUser)) return
    const ok = await deleteUser(selectedUser.id)
    if (ok) {
      toast.success("User deactivated.")
      setDeleteOpen(false)
    }
  }

  const toggleRole = (roleId: string, checked: boolean, target: "create" | "edit") => {
    if (!requireCapability(canAssignRoles)) return
    if (target === "create") {
      setCreateForm((current) => ({
        ...current,
        role_ids: checked
          ? [...current.role_ids, roleId]
          : current.role_ids.filter((id) => id !== roleId),
      }))
      return
    }
    setEditForm((current) => ({
      ...current,
      role_ids: checked
        ? [...current.role_ids, roleId]
        : current.role_ids.filter((id) => id !== roleId),
    }))
  }

  const submitApproveAdmin = async (userId: string) => {
    if (!requireCapability(canApproveUser)) return
    const ok = await approveAdmin(userId)
    if (ok) toast.success("Admin access approved.")
  }

  const columns: Column<AdminUserRead>[] = [
    {
      key: "identity",
      header: "User",
      cell: (row) => (
        <div className="flex flex-col">
          <span className="font-semibold">{displayUser(row)}</span>
          <span className="text-[11.5px] text-muted-foreground">{row.id.slice(0, 8)}</span>
        </div>
      ),
    },
    {
      key: "type",
      header: "Type",
      cell: (row) => <span className="text-sm capitalize">{row.user_type}</span>,
    },
    {
      key: "status",
      header: "Status",
      cell: (row) => <StatusBadge tone={statusTone[row.status] ?? "neutral"}>{row.status}</StatusBadge>,
    },
    {
      key: "approval",
      header: "Admin access",
      cell: (row) => (
        <StatusBadge tone={row.is_admin_approved ? "success" : "pending"} size="sm">
          {row.is_admin_approved ? "Approved" : "Pending"}
        </StatusBadge>
      ),
    },
    {
      key: "created",
      header: "Created",
      cell: (row) => <span className="text-muted-foreground">{formatDateTime(row.created_at)}</span>,
    },
    {
      key: "actions",
      header: "",
      align: "end",
      cell: (row) => (
        <div className="flex justify-end gap-2" onClick={(event) => event.stopPropagation()}>
          {!row.is_admin_approved && ["admin", "employee"].includes(row.user_type) ? (
            <Button size="sm" variant="outline" className="min-w-24" onClick={() => submitApproveAdmin(row.id)} disabled={isSubmitting || isAuthLoading || !canApproveUser}>
              <ShieldCheck className="h-3.5 w-3.5" />
              Approve
            </Button>
          ) : null}
          {["admin", "employee"].includes(row.user_type) ? (
            <Button size="sm" variant="ghost" className="min-w-20" onClick={() => openAllowlist(row)} disabled={isSubmitting || isAuthLoading || !canManageIp}>
              <ShieldCheck className="h-3.5 w-3.5" />
              IPs
            </Button>
          ) : null}
        </div>
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <PageHeader
        title="Users"
        description="Manage admin and employee access, pending approvals, temporary passwords, and per-user IP allowlists."
        breadcrumbs={[{ label: "System", href: "#" }, { label: "Users" }]}
        actions={
          <>
            <Button variant="outline" className="min-w-28" onClick={() => { fetchUsers(search); fetchPendingApprovals() }} disabled={isLoading}>
              <RefreshCw className="h-4 w-4" />
              Refresh
            </Button>
            <Button className="min-w-28" onClick={() => setCreateOpen(true)} disabled={isAuthLoading || !canCreateUser}>
              <PlusCircle className="h-4 w-4" />
              New user
            </Button>
          </>
        }
      />

      <div className="grid gap-4 md:grid-cols-4">
        <KpiCard label="Total users" value={String(users.length)} icon={Users} />
        <KpiCard label="Admins/employees" value={String(adminUsers)} icon={UserCog} tone="info" />
        <KpiCard label="Approved access" value={String(approvedAdmins)} icon={ShieldCheck} tone="success" />
        <KpiCard label="Must change password" value={String(passwordResetRequired)} icon={KeyRound} tone="warning" />
        <KpiCard label="Blocked IPs" value={String(activeBlacklistCount)} icon={Ban} tone="danger" />
      </div>

      {error ? (
        <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
      ) : null}

      {!isAuthLoading && !canUpdateUser && !canCreateUser ? (
        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
          Read-only access: your assigned permissions do not allow user changes.
        </div>
      ) : null}

      <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <div className="space-y-4">
          <FilterToolbar
            searchPlaceholder="Search email, phone, or user..."
            searchValue={search}
            onSearchChange={(value) => setSearch(value)}
            showDate={false}
            showExport={false}
            customFilters={
              <>
                <select
                  value={statusFilter}
                  onChange={(event) => setStatusFilter(event.target.value)}
                  className="h-9 rounded-md border border-border bg-card px-3 text-[12.5px]"
                >
                  <option value="">All statuses</option>
                  <option value="active">Active</option>
                  <option value="pending">Pending</option>
                  <option value="suspended">Suspended</option>
                  <option value="inactive">Inactive</option>
                </select>
                <select
                  value={typeFilter}
                  onChange={(event) => setTypeFilter(event.target.value)}
                  className="h-9 rounded-md border border-border bg-card px-3 text-[12.5px]"
                >
                  <option value="">All types</option>
                  <option value="admin">Admin</option>
                  <option value="employee">Employee</option>
                  <option value="customer">Customer</option>
                </select>
                <Button size="sm" variant="outline" onClick={() => fetchUsers(search)} disabled={isLoading}>
                  Search
                </Button>
              </>
            }
          />

          <SectionCard title="User directory">
            {isLoading ? (
              <div className="flex h-48 items-center justify-center">
                <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
              </div>
            ) : (
              <DataTable
                columns={columns}
                data={filteredUsers}
                rowKey={(row) => row.id}
                activeRowKey={selectedUser?.id}
                onRowClick={openUser}
                ariaLabel="Users directory"
              />
            )}
          </SectionCard>
        </div>

        <div className="space-y-4">
          <SectionCard title="Pending approvals" icon={<ShieldX className="h-4 w-4 text-amber-600" />}>
            {pendingApprovals.length === 0 ? (
              <p className="py-5 text-center text-sm text-muted-foreground">No pending admin approvals.</p>
            ) : (
              <div className="space-y-3">
                {pendingApprovals.map((user) => (
                  <div key={user.id} className="rounded-lg border border-border bg-card p-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="truncate text-sm font-semibold">{displayUser(user)}</p>
                        <p className="text-[11.5px] text-muted-foreground capitalize">{user.user_type}</p>
                      </div>
                      <Button size="sm" variant="outline" className="min-w-24" onClick={() => submitApproveAdmin(user.id)} disabled={isSubmitting || isAuthLoading || !canApproveUser}>
                        Approve
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </SectionCard>

          <SectionCard title="Selected user" icon={<UserCog className="h-4 w-4 text-gold-600" />}>
            {!selectedUser ? (
              <p className="py-8 text-center text-sm text-muted-foreground">Select a user to manage access.</p>
            ) : (
              <div className="space-y-4">
                <div>
                  <p className="text-sm font-semibold">{displayUser(selectedUser)}</p>
                  <p className="text-[11.5px] text-muted-foreground">{selectedUser.id}</p>
                </div>
                <div className="flex flex-wrap gap-2">
                  <StatusBadge tone={statusTone[selectedUser.status] ?? "neutral"}>{selectedUser.status}</StatusBadge>
                  <StatusBadge tone={selectedUser.is_admin_approved ? "success" : "pending"}>
                    {selectedUser.is_admin_approved ? "Admin approved" : "Approval pending"}
                  </StatusBadge>
                  {selectedUser.must_change_password ? <StatusBadge tone="warning">Password reset required</StatusBadge> : null}
                </div>
                <div className="rounded-lg border border-border bg-muted/30 p-3">
                  <p className="mb-2 text-[12px] font-semibold uppercase text-muted-foreground">Roles</p>
                  {selectedUserRoles.length === 0 ? (
                    <p className="text-sm text-muted-foreground">No roles assigned.</p>
                  ) : (
                    <div className="flex flex-wrap gap-2">
                      {selectedUserRoles.map((role) => (
                        <StatusBadge key={role.id} tone="gold" size="sm">{roleName(role)}</StatusBadge>
                      ))}
                    </div>
                  )}
                </div>
                <div className="grid gap-2">
                  <Button variant="outline" className="min-h-10" onClick={() => openEdit(selectedUser)} disabled={isSubmitting || isAuthLoading || !canUpdateUser}>Edit user</Button>
                  <Button variant="outline" className="min-h-10" onClick={() => openAllowlist(selectedUser)} disabled={isSubmitting || isAuthLoading || !canManageIp}>Manage IP allowlist</Button>
                  <Button variant="outline" className="min-h-10" onClick={() => { setGeneratedPassword(""); setPasswordOpen(true) }} disabled={isSubmitting || isAuthLoading || !canResetPassword}>
                    Regenerate password
                  </Button>
                  <Button variant="outline" className="min-h-10" onClick={submitRevokeSessions} disabled={isSubmitting || isAuthLoading || !canManageSessions}>
                    <LogOut className="h-4 w-4" /> Sign out all devices
                  </Button>
                  <Button variant="danger" className="min-h-10" onClick={() => setDeleteOpen(true)} disabled={isSubmitting || isAuthLoading || !canDisableUser}>
                    <Trash2 className="h-4 w-4" />
                    Deactivate user
                  </Button>
                </div>
              </div>
            )}
          </SectionCard>

          <SectionCard
            title="IP blacklist"
            description="Active login blocks"
            icon={<Ban className="h-4 w-4 text-red-600" />}
            actions={
              <Button size="sm" variant="outline" className="min-w-24" onClick={() => setBlacklistOpen(true)} disabled={protectedActionDisabled}>
                Block IP
              </Button>
            }
          >
            {blacklistEntries.length === 0 ? (
              <p className="py-5 text-center text-sm text-muted-foreground">No blocked IP addresses.</p>
            ) : (
              <div className="space-y-3">
                {blacklistEntries.slice(0, 6).map((entry) => (
                  <div key={entry.id} className="rounded-lg border border-border bg-card p-3">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          <p className="font-mono text-sm font-semibold">{entry.ip_address}</p>
                          <StatusBadge tone={entry.is_active ? "danger" : "neutral"} size="sm">
                            {entry.is_active ? "Active" : "Expired"}
                          </StatusBadge>
                        </div>
                        <p className="mt-1 line-clamp-2 text-[11.5px] text-muted-foreground">{entry.reason || "No reason"}</p>
                        <p className="mt-1 text-[11px] text-muted-foreground">
                          Blocked {formatDateTime(entry.blocked_at)}
                        </p>
                      </div>
                      {entry.is_active ? (
                        <Button
                          size="sm"
                          variant="ghost"
                          className="min-w-24"
                          onClick={() => {
                            setSelectedBlacklistEntry(entry)
                            setUnblockOpen(true)
                          }}
                          disabled={isSubmitting || protectedActionDisabled}
                        >
                          Unblock
                        </Button>
                      ) : null}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </SectionCard>
        </div>
      </div>

      <Modal open={createOpen} onClose={() => setCreateOpen(false)} title="Create admin user" size="lg">
        <div className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField label="Email" id="create-email" name="email" type="email" value={createForm.email ?? ""} onChange={(e) => setCreateForm((p) => ({ ...p, email: e.target.value }))} disabled={!canCreateUser} />
            <InputField label="Phone" id="create-phone" name="phone" value={createForm.phone ?? ""} onChange={(e) => setCreateForm((p) => ({ ...p, phone: e.target.value }))} disabled={!canCreateUser} />
            <InputField label="Arabic name" id="create-name" name="full_name_ar" value={createForm.full_name_ar ?? ""} onChange={(e) => setCreateForm((p) => ({ ...p, full_name_ar: e.target.value }))} disabled={!canCreateUser} />
            <div className="space-y-1">
              <label htmlFor="create-password" className="block text-sm font-medium text-foreground">
                Temporary password
              </label>
              <div className="relative">
                <input
                  id="create-password"
                  name="password"
                  type="text"
                  value={createForm.password ?? ""}
                  onChange={(e) => setCreateForm((p) => ({ ...p, password: e.target.value }))}
                  placeholder="Leave empty to generate"
                  disabled={!canCreateUser}
                  className="w-full rounded-lg border border-border bg-background py-2.5 pl-11 pr-3 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                />
                <button
                  type="button"
                  onClick={() => setCreateForm((p) => ({ ...p, password: generateTemporaryPassword() }))}
                  disabled={!canCreateUser}
                  className="absolute left-2 top-1/2 inline-flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition hover:bg-muted hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
                  aria-label="Generate temporary password"
                  title="Generate temporary password"
                >
                  <RefreshCw className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          </div>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={createForm.auto_approve} onChange={(e) => setCreateForm((p) => ({ ...p, auto_approve: e.target.checked }))} disabled={!canApproveUser} />
            Auto approve admin access
          </label>
          <RoleChecklist roles={roles} selectedIds={createForm.role_ids} onToggle={(roleId, checked) => toggleRole(roleId, checked, "create")} disabled={!canAssignRoles} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button>
            <Button onClick={submitCreate} isLoading={isSubmitting} disabled={!canCreateUser}>Create user</Button>
          </div>
        </div>
      </Modal>

      <Modal open={editOpen} onClose={() => setEditOpen(false)} title="Edit user" size="lg">
        <div className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <InputField label="Arabic name" id="edit-name" name="full_name_ar" value={editForm.full_name_ar ?? ""} onChange={(e) => setEditForm((p) => ({ ...p, full_name_ar: e.target.value }))} disabled={!canUpdateUser} />
            <InputField label="Email" id="edit-email" name="email" type="email" value={editForm.email ?? ""} onChange={(e) => setEditForm((p) => ({ ...p, email: e.target.value }))} disabled={!canUpdateUser} />
            <InputField label="Phone" id="edit-phone" name="phone" value={editForm.phone ?? ""} onChange={(e) => setEditForm((p) => ({ ...p, phone: e.target.value }))} disabled={!canUpdateUser} />
            <SelectField
              label="Status"
              id="edit-status"
              name="status"
              value={editForm.status ?? "active"}
              onChange={(e) => setEditForm((p) => ({ ...p, status: e.target.value }))}
              disabled={!canDisableUser}
              options={[
                { value: "active", label: "Active" },
                { value: "suspended", label: "Suspended" },
                { value: "inactive", label: "Inactive" },
              ]}
            />
          </div>
          <RoleChecklist roles={roles} selectedIds={editForm.role_ids} onToggle={(roleId, checked) => toggleRole(roleId, checked, "edit")} disabled={!canAssignRoles} />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
            <Button onClick={submitEdit} isLoading={isSubmitting} disabled={!canUpdateUser}>Save changes</Button>
          </div>
        </div>
      </Modal>

      <Modal open={allowlistOpen} onClose={() => setAllowlistOpen(false)} title="IP allowlist" description="One IPv4 or IPv6 address per line. The backend replaces the complete list on save." size="md">
        <div className="space-y-4">
          <TextAreaField label="Allowed IP addresses" id="allowlist" name="allowlist" value={allowlistText} rows={8} onChange={(e) => setAllowlistText(e.target.value)} disabled={!canManageIp} />
          <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[12.5px] text-amber-800">
            Saving an incorrect list can prevent this admin or employee from signing in.
          </div>
          {whitelistIps.length > 0 ? (
            <div className="text-[12px] text-muted-foreground">Current entries: {whitelistIps.join(", ")}</div>
          ) : null}
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setAllowlistOpen(false)}>Cancel</Button>
            <Button onClick={submitAllowlist} isLoading={isSubmitting} disabled={!canManageIp}>Save allowlist</Button>
          </div>
        </div>
      </Modal>

      <Modal
        open={allowlistConfirmOpen}
        onClose={() => {
          setAllowlistConfirmOpen(false)
          setPendingAllowlistIps([])
        }}
        title="Confirm IP allowlist"
        description="This replaces the complete allowed IP list for the selected user."
        size="sm"
      >
        <div className="space-y-4">
          <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[12.5px] text-amber-800">
            Confirm that these IP addresses are correct before saving. An incorrect list can block the user from signing in.
          </div>
          <div className="max-h-40 overflow-y-auto rounded-md border border-border bg-muted/30 p-3">
            {pendingAllowlistIps.length === 0 ? (
              <p className="text-sm text-muted-foreground">The allowlist will be empty.</p>
            ) : (
              <div className="space-y-1">
                {pendingAllowlistIps.map((ip) => (
                  <p key={ip} className="font-mono text-sm text-foreground">{ip}</p>
                ))}
              </div>
            )}
          </div>
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button
              variant="outline"
              onClick={() => {
                setAllowlistConfirmOpen(false)
                setPendingAllowlistIps([])
              }}
            >
              Review
            </Button>
            <Button onClick={confirmAllowlistSave} isLoading={isSubmitting} disabled={!canManageIp}>
              Confirm save
            </Button>
          </div>
        </div>
      </Modal>

      <Modal open={blacklistOpen} onClose={() => setBlacklistOpen(false)} title="Block IP address" description="Blocked IPs are rejected before admin username/password validation." size="md">
        <div className="space-y-4">
          <InputField
            label="IP address"
            id="blacklist-ip"
            name="ip_address"
            value={blacklistForm.ip_address}
            onChange={(e) => setBlacklistForm((p) => ({ ...p, ip_address: e.target.value }))}
            placeholder="203.0.113.10"
                  disabled={!canCreateUser}
            required
          />
          <TextAreaField
            label="Reason"
            id="blacklist-reason"
            name="reason"
            value={blacklistForm.reason}
            onChange={(e) => setBlacklistForm((p) => ({ ...p, reason: e.target.value }))}
            rows={3}
                  disabled={!canCreateUser}
            required
          />
          <InputField
            label="Expires at"
            id="blacklist-expires"
            name="expires_at"
            type="datetime-local"
            value={blacklistForm.expires_at}
            onChange={(e) => setBlacklistForm((p) => ({ ...p, expires_at: e.target.value }))}
            disabled={protectedActionDisabled}
          />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setBlacklistOpen(false)}>Cancel</Button>
            <Button variant="danger" onClick={submitBlacklist} isLoading={isSubmitting} disabled={protectedActionDisabled}>Block IP</Button>
          </div>
        </div>
      </Modal>

      <Modal
        open={blacklistConfirmOpen}
        onClose={() => {
          setBlacklistConfirmOpen(false)
          setPendingBlacklistEntry(null)
        }}
        title="Confirm IP block"
        description="This IP address will be blocked from admin authentication."
        size="sm"
      >
        <div className="space-y-4">
          <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-[12.5px] text-red-700">
            Blocking a shared or office IP can prevent multiple admins from signing in.
          </div>
          <div className="rounded-md border border-border bg-muted/30 p-3 text-sm">
            <p className="font-mono font-semibold text-foreground">{pendingBlacklistEntry?.ip_address}</p>
            <p className="mt-2 text-muted-foreground">{pendingBlacklistEntry?.reason}</p>
            {pendingBlacklistEntry?.expires_at ? (
              <p className="mt-2 text-[12px] text-muted-foreground">Expires: {pendingBlacklistEntry.expires_at}</p>
            ) : (
              <p className="mt-2 text-[12px] text-muted-foreground">No expiry set.</p>
            )}
          </div>
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button
              variant="outline"
              onClick={() => {
                setBlacklistConfirmOpen(false)
                setPendingBlacklistEntry(null)
              }}
            >
              Review
            </Button>
            <Button variant="danger" onClick={confirmBlacklistCreate} isLoading={isSubmitting} disabled={protectedActionDisabled}>
              Confirm block
            </Button>
          </div>
        </div>
      </Modal>

      <Modal open={unblockOpen} onClose={() => setUnblockOpen(false)} title="Unblock IP address" size="sm">
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Expire block for <span className="font-mono text-foreground">{selectedBlacklistEntry?.ip_address}</span>?
          </p>
          <TextAreaField
            label="Reason"
            id="unblock-reason"
            name="reason"
            value={unblockReason}
            onChange={(e) => setUnblockReason(e.target.value)}
            rows={3}
            placeholder="Optional unblock note"
            disabled={protectedActionDisabled}
          />
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setUnblockOpen(false)}>Cancel</Button>
            <Button onClick={submitUnblock} isLoading={isSubmitting} disabled={protectedActionDisabled}>Unblock</Button>
          </div>
        </div>
      </Modal>

      <Modal open={passwordOpen} onClose={() => setPasswordOpen(false)} title="Regenerate temporary password" size="sm">
        <div className="space-y-4">
          {generatedPassword ? (
            <div className="rounded-lg border border-border bg-muted/40 p-3">
              <p className="mb-1 text-[12px] font-semibold text-muted-foreground">Temporary password</p>
              <code className="block break-all rounded-md bg-background px-3 py-2 text-sm">{generatedPassword}</code>
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">This will set a new temporary password and require the user to change it.</p>
          )}
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setPasswordOpen(false)}>Close</Button>
            {!generatedPassword ? <Button onClick={submitRegeneratePassword} isLoading={isSubmitting} disabled={!canResetPassword}>Regenerate</Button> : null}
          </div>
        </div>
      </Modal>

      <Modal open={deleteOpen} onClose={() => setDeleteOpen(false)} title="Deactivate user" size="sm">
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">Deactivate {selectedUser ? displayUser(selectedUser) : "this user"}? The backend prevents deleting your own account.</p>
          <div className="flex justify-end gap-2 border-t border-border pt-4">
            <Button variant="outline" onClick={() => setDeleteOpen(false)}>Cancel</Button>
            <Button variant="danger" onClick={submitDelete} isLoading={isSubmitting} disabled={!canDisableUser}>Deactivate</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

function RoleChecklist({
  roles,
  selectedIds,
  onToggle,
  disabled = false,
}: {
  roles: AdminRoleRead[]
  selectedIds: string[]
  onToggle: (roleId: string, checked: boolean) => void
  disabled?: boolean
}) {
  if (roles.length === 0) {
    return <p className="rounded-md border border-border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">No roles available.</p>
  }

  return (
    <div className="rounded-lg border border-border">
      <div className="border-b border-border bg-muted/40 px-3 py-2 text-[12px] font-semibold uppercase text-muted-foreground">Roles</div>
      <div className="grid max-h-52 gap-2 overflow-y-auto p-3 md:grid-cols-2">
        {roles.map((role) => (
          <label key={role.id} className={`flex items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm ${disabled ? "opacity-60" : ""}`}>
            <input
              type="checkbox"
              checked={selectedIds.includes(role.id)}
              onChange={(event) => onToggle(role.id, event.target.checked)}
              disabled={disabled}
            />
            <span className="min-w-0 flex-1 truncate">{roleName(role)}</span>
            <span className="text-[11px] text-muted-foreground">{role.code}</span>
          </label>
        ))}
      </div>
    </div>
  )
}
