"use client";

import React, { useState, useEffect, useTransition } from "react";
import { useRouter } from "next/navigation";
import { SystemRoleId, ALL_PERMISSIONS, PermissionKey } from "@/types/auth";
import { createUserAction, toggleUserStatusAction } from "@/app/actions/admin.actions";
import { AdminUserListItem } from "@/lib/services/admin.service";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Users,
  UserPlus,
  Search,
  CheckCircle2,
  AlertCircle,
  Loader2,
  ShieldCheck,
  Briefcase,
  Home,
  UserCheck,
  Crown,
  Key,
  Check,
} from "lucide-react";
import { MdCorporateFare } from "react-icons/md";

interface AgencyOption {
  id: string;
  name: string;
  slug: string;
  is_verified?: boolean;
}

interface UserManagerProps {
  initialUsers: AdminUserListItem[];
  agencies: AgencyOption[];
}

const ROLE_METADATA: Record<
  SystemRoleId,
  { label: string; icon: React.ElementType; color: string; badgeClass: string; desc: string }
> = {
  SUPER_ADMIN: {
    label: "Super Admin",
    icon: Crown,
    color: "text-primary",
    badgeClass: "bg-primary/10 text-primary border-primary/20",
    desc: "Full platform owner with governance and system configuration access",
  },
  EMPLOYEE: {
    label: "Platform Staff",
    icon: ShieldCheck,
    color: "text-amber-500",
    badgeClass: "bg-amber-500/10 text-amber-600 dark:text-amber-300 border-amber-500/20",
    desc: "Internal staff member with scoped departmental permissions",
  },
  AGENCY_ADMIN: {
    label: "Agency Admin",
    icon: MdCorporateFare,
    color: "text-blue-500",
    badgeClass: "bg-blue-500/10 text-blue-600 dark:text-blue-300 border-blue-500/20",
    desc: "Real estate company owner managing firm listings, CAC credentials, and agents",
  },
  AGENT: {
    label: "Real Estate Agent",
    icon: Briefcase,
    color: "text-cyan-500",
    badgeClass: "bg-cyan-500/10 text-cyan-600 dark:text-cyan-300 border-cyan-500/20",
    desc: "Licensed or freelance agent listing properties and attending to buyer leads",
  },
  PROPERTY_OWNER: {
    label: "Property Owner",
    icon: Home,
    color: "text-emerald-500",
    badgeClass: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-300 border-emerald-500/20",
    desc: "Direct landlord or homeowner listing residential and commercial properties",
  },
  CUSTOMER: {
    label: "Client / Buyer",
    icon: Users,
    color: "text-slate-400",
    badgeClass: "bg-slate-500/10 text-slate-600 dark:text-slate-300 border-slate-500/20",
    desc: "Buyer, tenant, or investor searching properties and submitting inquiries",
  },
};

export function UserManager({ initialUsers, agencies }: UserManagerProps) {
  const router = useRouter();
  const [users, setUsers] = useState<AdminUserListItem[]>(initialUsers);
  const [isPending, startTransition] = useTransition();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedRoleFilter, setSelectedRoleFilter] = useState<string>("ALL");
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    const seen = new Set<string>();
    const deduped: AdminUserListItem[] = [];
    for (const u of initialUsers) {
      const key = u.id || u.email?.toLowerCase().trim();
      if (key && !seen.has(key)) {
        seen.add(key);
        deduped.push(u);
      }
    }
    setUsers(deduped);
  }, [initialUsers]);

  // User Creation Form State
  const [formRole, setFormRole] = useState<SystemRoleId>("CUSTOMER");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("+234");
  const [whatsappNumber, setWhatsappNumber] = useState("+234");
  const [password, setPassword] = useState("NigeriaListing2026!");

  // Agent Specific State
  const [agentAgencyId, setAgentAgencyId] = useState<string>("");
  const [agentRoleInAgency, setAgentRoleInAgency] = useState<"AGENT" | "COORDINATOR" | "ADMIN">("AGENT");

  // Agency Admin Specific State
  const [agencyName, setAgencyName] = useState("");
  const [cacRcNumber, setCacRcNumber] = useState("");
  const [taxIdNumber, setTaxIdNumber] = useState("");
  const [officeAddress, setOfficeAddress] = useState("");
  const [agencyPhone, setAgencyPhone] = useState("+234");

  // Staff Specific State
  const [jobTitle, setJobTitle] = useState("Listing Moderator");
  const [department, setDepartment] = useState("Operations");
  const [selectedPermissions, setSelectedPermissions] = useState<PermissionKey[]>([
    "property:approve_reject",
    "property:feature",
  ]);

  // Statistics Calculation
  const totalCount = users.length;
  const customersCount = users.filter((u) => u.roles.includes("CUSTOMER")).length;
  const agentsCount = users.filter((u) => u.roles.includes("AGENT")).length;
  const agenciesCount = users.filter((u) => u.roles.includes("AGENCY_ADMIN")).length;
  const staffCount = users.filter((u) => u.roles.includes("EMPLOYEE") || u.roles.includes("SUPER_ADMIN")).length;

  const filteredUsers = users.filter((u) => {
    // Role filter
    if (selectedRoleFilter !== "ALL" && !u.roles.includes(selectedRoleFilter as SystemRoleId)) {
      return false;
    }

    // Search filter
    if (!searchTerm.trim()) return true;
    const q = searchTerm.toLowerCase();
    const fullName = `${u.firstName || ""} ${u.lastName || ""}`.toLowerCase();
    return (
      fullName.includes(q) ||
      u.email.toLowerCase().includes(q) ||
      (u.phoneNumber && u.phoneNumber.includes(q)) ||
      (u.agency && u.agency.name.toLowerCase().includes(q)) ||
      (u.employee && u.employee.jobTitle.toLowerCase().includes(q))
    );
  });

  const togglePermission = (perm: PermissionKey) => {
    setSelectedPermissions((prev) =>
      prev.includes(perm) ? prev.filter((p) => p !== perm) : [...prev, perm]
    );
  };

  const handleSelectAllPermissions = () => {
    setSelectedPermissions(ALL_PERMISSIONS);
  };

  const handleClearPermissions = () => {
    setSelectedPermissions([]);
  };

  const handleCreateUser = (e: React.FormEvent) => {
    e.preventDefault();
    setMessage(null);

    startTransition(async () => {
      const res = await createUserAction({
        firstName,
        lastName,
        email,
        phoneNumber: phoneNumber || null,
        whatsappNumber: whatsappNumber || phoneNumber || null,
        password: password || null,
        role: formRole,
        agencyId: formRole === "AGENT" && agentAgencyId ? agentAgencyId : null,
        agentRoleInAgency: formRole === "AGENT" ? agentRoleInAgency : null,
        agencyName: formRole === "AGENCY_ADMIN" ? agencyName : null,
        cacRcNumber: formRole === "AGENCY_ADMIN" ? cacRcNumber : null,
        taxIdNumber: formRole === "AGENCY_ADMIN" ? taxIdNumber : null,
        officeAddress: formRole === "AGENCY_ADMIN" ? officeAddress : null,
        agencyPhone: formRole === "AGENCY_ADMIN" ? agencyPhone : null,
        jobTitle: formRole === "EMPLOYEE" ? jobTitle : null,
        department: formRole === "EMPLOYEE" ? department : null,
        permissions: formRole === "EMPLOYEE" ? selectedPermissions : null,
      });

      if (res.success) {
        setMessage({
          type: "success",
          text: `User account for "${firstName} ${lastName}" (${ROLE_METADATA[formRole].label}) created and provisioned successfully!`,
        });

        // Add to local state
        const newUserItem: AdminUserListItem = {
          id: res.user?.id || `usr-${Date.now()}`,
          clerkId: res.user?.clerk_id || "clerk_new",
          email,
          firstName,
          lastName,
          phoneNumber,
          whatsappNumber,
          avatarUrl: null,
          isActive: true,
          isSuspended: false,
          createdAt: new Date().toISOString(),
          roles: [formRole],
          employee:
            formRole === "EMPLOYEE"
              ? { jobTitle, department, permissions: selectedPermissions }
              : null,
          agency:
            formRole === "AGENCY_ADMIN"
              ? { id: "ag-new", name: agencyName || "New Agency", role: "ADMIN" }
              : formRole === "AGENT" && agentAgencyId
              ? {
                  id: agentAgencyId,
                  name: agencies.find((a) => a.id === agentAgencyId)?.name || "Agency Partner",
                  role: agentRoleInAgency,
                }
              : null,
        };

        setUsers((prev) => [newUserItem, ...prev]);

        // Reset form
        setFirstName("");
        setLastName("");
        setEmail("");
        setPhoneNumber("+234");
        setWhatsappNumber("+234");
        setAgencyName("");
        setCacRcNumber("");
        setTaxIdNumber("");
        setOfficeAddress("");
        setIsAddOpen(false);
        router.refresh();
      } else {
        setMessage({ type: "error", text: res.error || "Failed to create user account" });
      }
    });
  };

  const handleToggleStatus = (userId: string, currentActive: boolean) => {
    setMessage(null);
    startTransition(async () => {
      const res = await toggleUserStatusAction(userId, !currentActive);
      if (res.success) {
        setUsers((prev) =>
          prev.map((u) => (u.id === userId ? { ...u, isActive: !currentActive } : u))
        );
        setMessage({
          type: "success",
          text: `Account status updated to ${!currentActive ? "Active" : "Disabled"}`,
        });
        router.refresh();
      } else {
        setMessage({ type: "error", text: res.error || "Failed to update account status" });
      }
    });
  };

  return (
    <div className="space-y-6">
      {message && (
        <div
          className={`p-4 rounded-xl flex items-center gap-3 text-sm border shadow-sm ${
            message.type === "success"
              ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20"
              : "bg-destructive/10 text-destructive border-destructive/20"
          }`}
        >
          {message.type === "success" ? (
            <CheckCircle2 className="w-5 h-5 shrink-0" />
          ) : (
            <AlertCircle className="w-5 h-5 shrink-0" />
          )}
          <span>{message.text}</span>
        </div>
      )}

      {/* KPI Metric Summary Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
        <button onClick={() => setSelectedRoleFilter("ALL")} className="text-left transition-all group">
          <Card className={`border-border bg-card rounded-md shadow-2xs group-hover:border-foreground/40 transition-all ${selectedRoleFilter === "ALL" ? "ring-1 ring-primary/40 border-primary/30" : ""}`}>
            <CardContent className="p-3.5 flex items-center justify-between">
              <div>
                <p className="text-[11px] text-muted-foreground font-medium group-hover:text-foreground transition-colors">Total Registered</p>
                <p className="text-xl font-bold tracking-tight text-foreground mt-0.5">{totalCount}</p>
              </div>
              <Users className="w-4 h-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </button>

        <button onClick={() => setSelectedRoleFilter("CUSTOMER")} className="text-left transition-all group">
          <Card className={`border-border bg-card rounded-md shadow-2xs group-hover:border-foreground/40 transition-all ${selectedRoleFilter === "CUSTOMER" ? "ring-1 ring-primary/40 border-primary/30" : ""}`}>
            <CardContent className="p-3.5 flex items-center justify-between">
              <div>
                <p className="text-[11px] text-muted-foreground font-medium group-hover:text-foreground transition-colors">Clients / Buyers</p>
                <p className="text-xl font-bold tracking-tight text-foreground mt-0.5">{customersCount}</p>
              </div>
              <UserCheck className="w-4 h-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </button>

        <button onClick={() => setSelectedRoleFilter("AGENT")} className="text-left transition-all group">
          <Card className={`border-border bg-card rounded-md shadow-2xs group-hover:border-foreground/40 transition-all ${selectedRoleFilter === "AGENT" ? "ring-1 ring-primary/40 border-primary/30" : ""}`}>
            <CardContent className="p-3.5 flex items-center justify-between">
              <div>
                <p className="text-[11px] text-muted-foreground font-medium group-hover:text-foreground transition-colors">Agents</p>
                <p className="text-xl font-bold tracking-tight text-foreground mt-0.5">{agentsCount}</p>
              </div>
              <Briefcase className="w-4 h-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </button>

        <button onClick={() => setSelectedRoleFilter("AGENCY_ADMIN")} className="text-left transition-all group">
          <Card className={`border-border bg-card rounded-md shadow-2xs group-hover:border-foreground/40 transition-all ${selectedRoleFilter === "AGENCY_ADMIN" ? "ring-1 ring-primary/40 border-primary/30" : ""}`}>
            <CardContent className="p-3.5 flex items-center justify-between">
              <div>
                <p className="text-[11px] text-muted-foreground font-medium group-hover:text-foreground transition-colors">Agencies</p>
                <p className="text-xl font-bold tracking-tight text-foreground mt-0.5">{agenciesCount}</p>
              </div>
              <MdCorporateFare className="w-4 h-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </button>

        <button onClick={() => setSelectedRoleFilter("EMPLOYEE")} className="text-left transition-all group">
          <Card className={`border-border bg-card rounded-md shadow-2xs group-hover:border-foreground/40 transition-all ${selectedRoleFilter === "EMPLOYEE" || selectedRoleFilter === "SUPER_ADMIN" ? "ring-1 ring-primary/40 border-primary/30" : ""}`}>
            <CardContent className="p-3.5 flex items-center justify-between">
              <div>
                <p className="text-[11px] text-muted-foreground font-medium group-hover:text-foreground transition-colors">Staff & Admins</p>
                <p className="text-xl font-bold tracking-tight text-foreground mt-0.5">{staffCount}</p>
              </div>
              <ShieldCheck className="w-4 h-4 text-muted-foreground" />
            </CardContent>
          </Card>
        </button>
      </div>

      {/* Control Bar: Search & Multi-Role Create User Button */}
      <div className="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-4">
        {/* Role Filter Tabs */}
        <div className="flex items-center gap-1.5 overflow-x-auto pb-1 max-w-full">
          {[
            { id: "ALL", label: `All Users (${totalCount})` },
            { id: "CUSTOMER", label: `Clients (${customersCount})` },
            { id: "AGENT", label: `Agents (${agentsCount})` },
            { id: "AGENCY_ADMIN", label: `Agencies (${agenciesCount})` },
            { id: "PROPERTY_OWNER", label: `Landlords (${users.filter((u) => u.roles.includes("PROPERTY_OWNER")).length})` },
            { id: "EMPLOYEE", label: `Staff (${users.filter((u) => u.roles.includes("EMPLOYEE")).length})` },
            { id: "SUPER_ADMIN", label: `Super Admins (${users.filter((u) => u.roles.includes("SUPER_ADMIN")).length})` },
          ].map((tab) => (
            <Button
              key={tab.id}
              variant={selectedRoleFilter === tab.id ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedRoleFilter(tab.id)}
              className={`text-xs whitespace-nowrap h-8 px-3 rounded-md cursor-pointer ${
                selectedRoleFilter === tab.id
                  ? "bg-primary hover:bg-primary/90 text-primary-foreground font-semibold shadow-2xs"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {tab.label}
            </Button>
          ))}
        </div>

        {/* Search & Actions */}
        <div className="flex items-center gap-2">
          <div className="relative flex-1 sm:w-64">
            <Search className="w-3.5 h-3.5 absolute left-2.5 top-2.5 text-muted-foreground" />
            <Input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search by name, email, phone..."
              className="pl-8 h-8 text-xs rounded-md"
            />
          </div>

          <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
            <DialogTrigger className={buttonVariants({ className: "bg-primary hover:bg-primary/90 text-primary-foreground gap-1.5 font-semibold shadow-2xs text-xs h-8 px-3 rounded-md cursor-pointer shrink-0" })}>
              <UserPlus className="w-3.5 h-3.5" />
              <span>Create User</span>
            </DialogTrigger>
            <DialogContent className="max-w-xl max-h-[90vh] overflow-y-auto rounded-md">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2 text-sm">
                  <UserPlus className="w-4 h-4 text-foreground" />
                  Provision New User Account
                </DialogTitle>
                <DialogDescription className="text-xs">
                  Create and provision any user type across Nigeria: buyers, agents, agencies, landlords, staff, or admins.
                </DialogDescription>
              </DialogHeader>

              <form onSubmit={handleCreateUser} className="space-y-4 pt-3 text-xs">
                {/* 1. Select User Role */}
                <div className="space-y-2">
                  <Label className="font-semibold text-xs text-foreground">Select User Role & Identity</Label>
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                    {(Object.keys(ROLE_METADATA) as SystemRoleId[]).map((roleKey) => {
                      const meta = ROLE_METADATA[roleKey];
                      const Icon = meta.icon;
                      const isSelected = formRole === roleKey;
                      return (
                        <button
                          key={roleKey}
                          type="button"
                          onClick={() => setFormRole(roleKey)}
                          className={`p-2.5 rounded-xl border text-left flex flex-col justify-between transition-all cursor-pointer ${
                            isSelected
                              ? "border-primary bg-primary/10 ring-1 ring-primary shadow-sm"
                              : "border-border bg-card/60 hover:bg-muted/40"
                          }`}
                        >
                          <div className="flex items-center justify-between w-full mb-1">
                            <Icon className={`w-4 h-4 ${meta.color}`} />
                            {isSelected && <Check className="w-3.5 h-3.5 text-primary" />}
                          </div>
                          <div>
                            <p className="font-bold text-xs text-foreground">{meta.label}</p>
                            <p className="text-[10px] text-muted-foreground line-clamp-1">{roleKey}</p>
                          </div>
                        </button>
                      );
                    })}
                  </div>
                  <p className="text-[11px] text-muted-foreground italic bg-muted/40 p-2 rounded-lg">
                    {ROLE_METADATA[formRole].desc}
                  </p>
                </div>

                {/* 2. Personal Information */}
                <div className="space-y-3 pt-2 border-t border-border">
                  <Label className="font-semibold text-xs flex items-center gap-1.5">
                    <UserCheck className="w-3.5 h-3.5 text-primary" />
                    Personal & Account Credentials
                  </Label>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-1">
                      <Label htmlFor="firstName">First Name</Label>
                      <Input
                        id="firstName"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        placeholder="e.g. Babatunde"
                        required
                        className="h-8 text-xs"
                      />
                    </div>
                    <div className="space-y-1">
                      <Label htmlFor="lastName">Last Name</Label>
                      <Input
                        id="lastName"
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        placeholder="e.g. Fashola"
                        required
                        className="h-8 text-xs"
                      />
                    </div>
                  </div>

                  <div className="space-y-1">
                    <Label htmlFor="userEmail">Email Address</Label>
                    <Input
                      id="userEmail"
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      placeholder="user@example.com"
                      required
                      className="h-8 text-xs"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="space-y-1">
                      <Label htmlFor="phoneNumber">Phone Number</Label>
                      <Input
                        id="phoneNumber"
                        value={phoneNumber}
                        onChange={(e) => setPhoneNumber(e.target.value)}
                        placeholder="+2348012345678"
                        className="h-8 text-xs"
                      />
                    </div>
                    <div className="space-y-1">
                      <Label htmlFor="whatsappNumber">WhatsApp Number</Label>
                      <Input
                        id="whatsappNumber"
                        value={whatsappNumber}
                        onChange={(e) => setWhatsappNumber(e.target.value)}
                        placeholder="+2348012345678"
                        className="h-8 text-xs"
                      />
                    </div>
                  </div>

                  <div className="space-y-1">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="password">Initial Password</Label>
                      <button
                        type="button"
                        onClick={() => setPassword(`Jaz${Math.random().toString(36).slice(2, 6)}!2026`)}
                        className="text-[10px] text-primary hover:underline cursor-pointer"
                      >
                        Generate random
                      </button>
                    </div>
                    <Input
                      id="password"
                      type="text"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="Initial login password"
                      className="h-8 text-xs font-mono"
                    />
                  </div>
                </div>

                {/* 3. Conditional: Real Estate Agent Setup */}
                {formRole === "AGENT" && (
                  <div className="space-y-3 pt-2 border-t border-border bg-cyan-500/5 p-3 rounded-xl border-cyan-500/20">
                    <Label className="font-semibold text-xs text-cyan-700 dark:text-cyan-300 flex items-center gap-1.5">
                      <Briefcase className="w-3.5 h-3.5" />
                      Agency Affiliation & Agent Designation
                    </Label>

                    <div className="space-y-1.5">
                      <Label htmlFor="agentAgency">Select Affiliated Real Estate Agency (Optional)</Label>
                      <select
                        id="agentAgency"
                        value={agentAgencyId}
                        onChange={(e) => setAgentAgencyId(e.target.value)}
                        className="w-full h-8 text-xs rounded-md border border-input bg-background px-3 py-1 text-foreground"
                      >
                        <option value="">Independent Agent (No agency affiliation)</option>
                        {agencies.map((ag) => (
                          <option key={ag.id} value={ag.id}>
                            {ag.name} {ag.is_verified ? "✓ Verified" : ""}
                          </option>
                        ))}
                      </select>
                    </div>

                    {agentAgencyId && (
                      <div className="space-y-1.5">
                        <Label htmlFor="agentRoleInAgency">Role in Agency</Label>
                        <select
                          id="agentRoleInAgency"
                          value={agentRoleInAgency}
                          onChange={(e: any) => setAgentRoleInAgency(e.target.value)}
                          className="w-full h-8 text-xs rounded-md border border-input bg-background px-3 py-1 text-foreground"
                        >
                          <option value="AGENT">Standard Agent</option>
                          <option value="COORDINATOR">Senior Coordinator</option>
                          <option value="ADMIN">Agency Co-Administrator</option>
                        </select>
                      </div>
                    )}
                  </div>
                )}

                {/* 4. Conditional: Real Estate Agency Admin Setup */}
                {formRole === "AGENCY_ADMIN" && (
                  <div className="space-y-3 pt-2 border-t border-border bg-blue-500/5 p-3 rounded-xl border-blue-500/20">
                    <Label className="font-semibold text-xs text-blue-700 dark:text-blue-300 flex items-center gap-1.5">
                      <MdCorporateFare className="w-3.5 h-3.5" />
                      Corporate Real Estate Agency Details
                    </Label>

                    <div className="space-y-1.5">
                      <Label htmlFor="agencyName">Agency / Company Name</Label>
                      <Input
                        id="agencyName"
                        value={agencyName}
                        onChange={(e) => setAgencyName(e.target.value)}
                        placeholder="e.g. Prime Realty Nigeria Ltd"
                        required
                        className="h-8 text-xs"
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <Label htmlFor="cacRcNumber">CAC RC Number</Label>
                        <Input
                          id="cacRcNumber"
                          value={cacRcNumber}
                          onChange={(e) => setCacRcNumber(e.target.value)}
                          placeholder="e.g. RC-1849201"
                          className="h-8 text-xs"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label htmlFor="taxIdNumber">Tax ID (TIN)</Label>
                        <Input
                          id="taxIdNumber"
                          value={taxIdNumber}
                          onChange={(e) => setTaxIdNumber(e.target.value)}
                          placeholder="e.g. TIN-29481029"
                          className="h-8 text-xs"
                        />
                      </div>
                    </div>

                    <div className="space-y-1">
                      <Label htmlFor="officeAddress">Official Office Address</Label>
                      <Input
                        id="officeAddress"
                        value={officeAddress}
                        onChange={(e) => setOfficeAddress(e.target.value)}
                        placeholder="e.g. Plot 12, Admiralty Way, Lekki Phase 1, Lagos"
                        className="h-8 text-xs"
                      />
                    </div>
                  </div>
                )}

                {/* 5. Conditional: Platform Staff / Employee Setup */}
                {formRole === "EMPLOYEE" && (
                  <div className="space-y-3 pt-2 border-t border-border bg-amber-500/5 p-3 rounded-xl border-amber-500/20">
                    <Label className="font-semibold text-xs text-amber-700 dark:text-amber-300 flex items-center gap-1.5">
                      <ShieldCheck className="w-3.5 h-3.5" />
                      Departmental Role & Permissions
                    </Label>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <Label htmlFor="jobTitle">Job Title</Label>
                        <Input
                          id="jobTitle"
                          value={jobTitle}
                          onChange={(e) => setJobTitle(e.target.value)}
                          placeholder="e.g. Property Listing Moderator"
                          required
                          className="h-8 text-xs"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label htmlFor="department">Department</Label>
                        <Input
                          id="department"
                          value={department}
                          onChange={(e) => setDepartment(e.target.value)}
                          placeholder="e.g. Operations / Moderation"
                          required
                          className="h-8 text-xs"
                        />
                      </div>
                    </div>

                    {/* Permissions checklist */}
                    <div className="space-y-1.5 pt-1">
                      <div className="flex items-center justify-between">
                        <Label className="text-[11px] font-medium flex items-center gap-1">
                          <Key className="w-3 h-3 text-amber-600" />
                          Granular Staff Privileges
                        </Label>
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={handleSelectAllPermissions}
                            className="text-[10px] text-amber-600 hover:underline cursor-pointer"
                          >
                            Select All
                          </button>
                          <span className="text-muted-foreground text-[10px]">•</span>
                          <button
                            type="button"
                            onClick={handleClearPermissions}
                            className="text-[10px] text-muted-foreground hover:underline cursor-pointer"
                          >
                            Clear
                          </button>
                        </div>
                      </div>

                      <div className="space-y-1 max-h-36 overflow-y-auto p-2 border border-border rounded-lg bg-background">
                        {ALL_PERMISSIONS.map((perm: PermissionKey) => {
                          const isChecked = selectedPermissions.includes(perm);
                          return (
                            <label
                              key={perm}
                              className="flex items-center gap-2 p-1 rounded hover:bg-muted cursor-pointer text-xs"
                            >
                              <input
                                type="checkbox"
                                checked={isChecked}
                                onChange={() => togglePermission(perm)}
                                className="rounded border-input text-amber-600 focus:ring-amber-500"
                              />
                              <span className="font-mono text-[10px] text-foreground">{perm}</span>
                            </label>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                )}

                <Button
                  type="submit"
                  disabled={isPending || (formRole === "EMPLOYEE" && selectedPermissions.length === 0)}
                  className="w-full bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-xs h-9 mt-2 cursor-pointer shadow-xs"
                >
                  {isPending ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" /> Provisioning Account...
                    </>
                  ) : (
                    `Create & Provision ${ROLE_METADATA[formRole].label}`
                  )}
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Users Table */}
      <Card className="border-border rounded-md shadow-2xs overflow-hidden">
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/40">
                <TableHead className="text-xs font-semibold">User & Identity</TableHead>
                <TableHead className="text-xs font-semibold">System Role</TableHead>
                <TableHead className="text-xs font-semibold">Affiliation / Department</TableHead>
                <TableHead className="text-xs font-semibold">Contact Info</TableHead>
                <TableHead className="text-xs font-semibold">Status</TableHead>
                <TableHead className="text-right text-xs font-semibold">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredUsers.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="py-6 text-center text-muted-foreground text-xs">
                    <Users className="w-4 h-4 mx-auto mb-1 text-muted-foreground/60" />
                    <p className="font-medium text-foreground">No platform users found matching your criteria.</p>
                  </TableCell>
                </TableRow>
              ) : (
                filteredUsers.map((u, idx) => {
                  const fullName =
                    u.firstName || u.lastName
                      ? `${u.firstName || ""} ${u.lastName || ""}`.trim()
                      : "Registered User";
                  const primaryRole = u.roles[0] || "CUSTOMER";
                  const meta = ROLE_METADATA[primaryRole] || ROLE_METADATA.CUSTOMER;
                  const Icon = meta.icon;

                  return (
                    <TableRow key={`${u.id}-${idx}`} className="hover:bg-muted/30">
                      {/* Name & Email */}
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center font-bold text-xs text-foreground shrink-0 border border-border">
                            {u.avatarUrl ? (
                              // eslint-disable-next-line @next/next/no-img-element
                              <img
                                src={u.avatarUrl}
                                alt={fullName}
                                className="w-full h-full rounded-full object-cover"
                              />
                            ) : (
                              (u.firstName?.[0] || "U").toUpperCase()
                            )}
                          </div>
                          <div className="space-y-0.5 min-w-0">
                            <p className="font-bold text-xs text-foreground truncate">{fullName}</p>
                            <p className="text-[11px] text-muted-foreground truncate">{u.email}</p>
                          </div>
                        </div>
                      </TableCell>

                      {/* Role Badges */}
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {u.roles.map((r) => {
                            const rMeta = ROLE_METADATA[r] || ROLE_METADATA.CUSTOMER;
                            const RIcon = rMeta.icon;
                            return (
                              <span
                                key={r}
                                className="inline-flex items-center gap-1 text-[10px] font-medium py-0.5 px-2 rounded border border-border bg-muted/60 text-foreground"
                              >
                                <RIcon className="w-3 h-3 text-muted-foreground" />
                                {rMeta.label}
                              </span>
                            );
                          })}
                        </div>
                      </TableCell>

                      {/* Affiliation / Department */}
                      <TableCell>
                        {u.agency ? (
                          <div className="space-y-0.5 text-xs">
                            <div className="flex items-center gap-1 font-medium text-foreground">
                              <MdCorporateFare className="w-3 h-3 text-muted-foreground" />
                              <span className="truncate max-w-[160px]">{u.agency.name}</span>
                            </div>
                            <span className="text-[10px] text-muted-foreground font-mono">
                              Role: {u.agency.role}
                            </span>
                          </div>
                        ) : u.employee ? (
                          <div className="space-y-0.5 text-xs">
                            <p className="font-medium text-foreground">{u.employee.jobTitle}</p>
                            <p className="text-[10px] text-muted-foreground">{u.employee.department}</p>
                          </div>
                        ) : (
                          <span className="text-xs text-muted-foreground italic">Independent</span>
                        )}
                      </TableCell>

                      {/* Contact Info */}
                      <TableCell>
                        <div className="space-y-0.5 text-[11px]">
                          <p className="text-foreground">{u.phoneNumber || "No phone"}</p>
                          <p className="text-muted-foreground text-[10px]">
                            Joined: {new Date(u.createdAt).toLocaleDateString()}
                          </p>
                        </div>
                      </TableCell>

                      {/* Status */}
                      <TableCell>
                        <span
                          className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${
                            u.isActive
                              ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border border-emerald-500/20"
                              : "bg-muted text-muted-foreground border border-border"
                          }`}
                        >
                          {u.isActive ? "Active" : "Disabled"}
                        </span>
                      </TableCell>

                      {/* Action */}
                      <TableCell className="text-right">
                        <Button
                          size="sm"
                          variant="ghost"
                          disabled={isPending}
                          onClick={() => handleToggleStatus(u.id, u.isActive)}
                          className="h-7 text-xs text-muted-foreground hover:text-foreground cursor-pointer rounded"
                        >
                          {u.isActive ? "Disable Access" : "Enable Access"}
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
