"use client";

import { useState, useEffect, useCallback, useRef, useMemo, type JSX } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { TablePagination } from "@/components/ui/table-pagination";
import { UserPerformanceSummary } from "@/components/dashboard/user-performance-summary";
import { PasswordResetModal } from "@/components/users/password-reset-modal";
import { EditUserModal } from "@/components/users/edit-user-modal";
import {
  formatDate,
  calculateEmploymentStatus,
  getEmploymentStatusBadgeColor,
  calculateGrowthEligibility,
  getGrowthEligibilityBadgeColor,
} from "@/lib/date-utils";
import { toast } from "@/hooks/use-toast";
import { api } from "@/lib/store/api";
import { apiCall } from "@/lib/store/api-call";
import {
  Users,
  UserPlus,
  Search,
  MoreHorizontal,
  Mail,
  Building,
  Calendar,
  Shield,
  Crown,
  Star,
  User as UserIcon,
  Briefcase,
  Key,
  Code,
  UserX,
  AlertTriangle,
  Grid3X3,
  List,
  UserCheck,
  Network,
} from "lucide-react";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Skeleton } from "@/components/ui/skeleton";
import { UsersPageSkeleton } from "@/components/ui/loading-skeletons";
import { AppSpinner } from "@/components/ui/app-loader";
import { DatePicker } from "@/components/ui/date-picker";
import { UsersFilterPanel } from "@/components/users/users-filter-panel";
import type { UsersFilterCategory } from "@/components/users/users-filter-panel";
import { UsersPageExportMenu } from "@/components/users/users-page-export-menu";
import type { UsersPageExportPerson } from "@/lib/users-page-export";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface ApiUser {
  id: string;
  employeeId: string;
  name: string;
  username: string;
  email: string;
  role: string;
  position: string;
  department: string;
  joinDate: string;
  salary?: number;
  phone?: string;
  avatar?: string;
  isActive: boolean;
  ssoPending?: boolean;
  ssoRevoked?: boolean;
  createdAt: string;
  updatedAt: string;
  totalLoggedHours: number;
  employmentType?: string; // Added for edit functionality
  managerId?: string; // Added for checking reporting relationships
  techStack?: string; // Added for Production department tech stack
  designSubTeam?: string; // Added for Design department sub-team
  _count: {
    projects: number;
    monthlyPerformance: number;
    loggedHours: number;
  };
  projects?: {
    project: {
      id: string;
      name: string;
      status: string;
    };
  }[]; // Added for project details
  managerName?: string; // Added for reporting manager
  manager?: {
    id: string;
    name: string;
    role: string;
    position: string;
  }; // Added for manager relation
}

interface UsersSummary {
  total: number;
  workforce: number;
  active: number;
  departments: number;
  teamLeads: number;
  members: number;
  managers: number;
  unitLeads: number;
  upperManagement: number;
  superAdmins: number;
  byRole: Record<string, number>;
  logEntries: number;
  hoursLogged: number;
}

interface UsersResponse {
  users: ApiUser[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    pages: number;
  };
  summary?: UsersSummary;
  currentUserRole: string;
  accessLevel: {
    canViewAll: boolean;
    canViewManagement: boolean;
    canViewSubordinates: boolean;
    canCreateUsers: boolean;
    canEditUsers: boolean;
    canRemoveUsers?: boolean;
    viewScope: string;
  };
}

const getRoleBadgeColor = (role: string) => {
  const colors = {
    SUPER_ADMIN: "bg-red-100 text-red-800 border-red-200",
    UPPER_MANAGEMENT: "bg-primary/10 text-primary border-primary/20",
    MANAGER: "bg-emerald-100 text-emerald-800 border-emerald-200",
    UNIT_LEAD: "bg-orange-100 text-orange-800 border-orange-200",
    MEMBER: "bg-muted text-foreground border-border",
  };
  return (
    colors[role as keyof typeof colors] ||
    "bg-muted text-foreground border-border"
  );
};

const getRoleIcon = (role: string) => {
  const icons = {
    SUPER_ADMIN: Crown,
    UPPER_MANAGEMENT: Shield,
    MANAGER: Star,
    UNIT_LEAD: Users,
    MEMBER: UserIcon,
  };
  const IconComponent = icons[role as keyof typeof icons] || UserIcon;
  return <IconComponent className="h-3 w-3" />;
};

const getRoleDisplayName = (role: string) => {
  const names = {
    SUPER_ADMIN: "Super Admin",
    UPPER_MANAGEMENT: "Top Management",
    MANAGER: "Manager",
    UNIT_LEAD: "Unit Lead",
    MEMBER: "Member",
  };
  return names[role as keyof typeof names] || role;
};

type UserKpiSummary = {
  loggedHours: number;
  expectedDays: number;
  actualProjects: number;
};

const EMPTY_KPI: UserKpiSummary = {
  loggedHours: 0,
  expectedDays: 0,
  actualProjects: 0,
};

/** One batched request for all visible users — replaces per-row N+1 KPI fetches. */
function useUsersKpiBatch(userIds: string[], dateFrom: string, dateTo: string) {
  const [kpis, setKpis] = useState<Record<string, UserKpiSummary>>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const idsKey = userIds.join(",");

  useEffect(() => {
    if (!idsKey) {
      setKpis({});
      setLoading(false);
      setError(null);
      return;
    }

    let isMounted = true;

    async function load() {
      setLoading(true);
      setError(null);
      try {
        const data = await apiCall<{ kpis?: Record<string, UserKpiSummary> }>(
          api.endpoints.getKpiSummary.initiate({
            userIds: idsKey,
            startDate: dateFrom,
            endDate: dateTo,
          }),
        );
        if (isMounted) {
          setKpis(data.kpis || {});
          setLoading(false);
        }
      } catch {
        if (isMounted) {
          setKpis({});
          setLoading(false);
          setError("Failed to load KPI");
        }
      }
    }

    load();
    return () => {
      isMounted = false;
    };
  }, [idsKey, dateFrom, dateTo]);

  return { kpis, loading, error };
}

// New UserCardWithKPI component
interface UserCardWithKPIProps {
  user: ApiUser;
  accessLevel: {
    canViewAll: boolean;
    canViewManagement: boolean;
    canCreateUsers: boolean;
    canEditUsers: boolean;
    canRemoveUsers?: boolean;
  };
  getInitials: (name: string) => string;
  getRoleBadgeColor: (role: string) => string;
  getRoleIcon: (role: string) => JSX.Element | null;
  getRoleDisplayName: (role: string) => string;
  handleEditUser: (user: ApiUser) => void;
  canResetPassword: (user: ApiUser) => boolean;
  canMarkInactive: (user: ApiUser) => boolean;
  handlePasswordReset: (user: ApiUser) => void;
  handleRemoveUser: (user: ApiUser) => void;
  canMarkActive: (user: ApiUser) => boolean;
  handleReactivateUser: (user: ApiUser) => void;
  formatDate: (
    dateString: string,
    options?: { includeTime?: boolean; format?: "short" | "medium" | "long" },
  ) => string;
  kpi: UserKpiSummary;
  kpiLoading: boolean;
  kpiError: string | null;
}

function getProjectExpectation(
  department: string,
  role: string,
  techStack?: string,
) {
  if (department === "Production") {
    return techStack === "Backend" ? 12 : techStack === "Frontend" ? 6 : 9;
  }

  switch (role) {
    case "SUPER_ADMIN":
    case "UPPER_MANAGEMENT":
      return department === "Engineering"
        ? 8
        : department === "Product"
          ? 10
          : department === "Design"
            ? 6
            : 4;
    case "MANAGER":
      return department === "Engineering"
        ? 6
        : department === "Product"
          ? 8
          : department === "Design"
            ? 5
            : department === "Marketing"
              ? 4
              : department === "Sales"
                ? 5
                : 3;
    case "UNIT_LEAD":
      return department === "Engineering"
        ? 4
        : department === "Product"
          ? 5
          : department === "Design"
            ? 4
            : department === "Marketing"
              ? 3
              : department === "Sales"
                ? 4
                : 2;
    case "MEMBER":
      return department === "Engineering"
        ? 3
        : department === "Product"
          ? 3
          : department === "Design"
            ? 2
            : department === "Marketing"
              ? 2
              : department === "Sales"
                ? 3
                : 1;
    default:
      return 2;
  }
}

function UserCardWithKPI({
  user,
  accessLevel,
  getInitials,
  getRoleBadgeColor,
  getRoleIcon,
  getRoleDisplayName,
  handleEditUser,
  canResetPassword,
  canMarkInactive,
  handlePasswordReset,
  handleRemoveUser,
  canMarkActive,
  handleReactivateUser,
  formatDate,
  kpi,
  kpiLoading,
  kpiError,
}: UserCardWithKPIProps) {
  const router = useRouter();
  const { loggedHours, expectedDays, actualProjects } = kpi;
  const canSeeInactiveStatus =
    accessLevel.canViewAll ||
    accessLevel.canViewManagement ||
    !!accessLevel.canRemoveUsers;
  const showActions =
    accessLevel.canEditUsers ||
    accessLevel.canViewAll ||
    !!accessLevel.canRemoveUsers;
  const isInactive = !user.isActive && canSeeInactiveStatus;
  const expectedProjects = getProjectExpectation(
    user.department,
    user.role,
    user.techStack,
  );
  const expectedHours = expectedDays * 8;
  const hoursPct =
    expectedHours > 0 ? (loggedHours / expectedHours) * 100 : null;

  const metaItems = [
    {
      icon: Mail,
      label: "Email",
      value: user.email,
      title: user.email,
    },
    {
      icon: UserIcon,
      label: "Employee ID",
      value: user.employeeId || "Not assigned",
    },
    ...(user.manager
      ? [
          {
            icon: Network,
            label: "Reports to",
            value: `${user.manager.name}`,
            title: `${user.manager.name} (${user.manager.role})`,
          },
        ]
      : []),
    {
      icon: Calendar,
      label: "Joined",
      value: formatDate(user.joinDate, { format: "short" }),
    },
    ...(user.department === "Production" && user.techStack
      ? [
          {
            icon: Code,
            label: "Tech stack",
            value: user.techStack,
          },
        ]
      : []),
  ];

  return (
    <Card
      className={cn(
        "group relative overflow-hidden p-0 cursor-pointer transition-shadow duration-200 hover:shadow-md",
        isInactive && "opacity-70 border-destructive/30 bg-destructive/[0.03]",
      )}
      onClick={() => router.push(`/dashboard/users/${user.id}`)}
    >
      {isInactive && (
        <Badge
          variant="destructive"
          className="absolute right-3 top-3 z-10 px-2 py-0 text-[10px] font-medium"
        >
          Inactive
        </Badge>
      )}
      {!isInactive && <SsoBadge user={user} className="absolute right-3 top-3 z-10" />}

      <div className="p-4 pb-3">
        <div className="flex items-start gap-3">
          <Avatar className="h-11 w-11 shrink-0 border border-border">
            <AvatarFallback className="text-sm font-semibold">
              {getInitials(user.name)}
            </AvatarFallback>
          </Avatar>

          <div className="min-w-0 flex-1">
            <div className="flex items-start justify-between gap-2">
              <div className="min-w-0">
                <h3
                  className={cn(
                    "truncate text-[15px] font-semibold tracking-tight text-foreground",
                    isInactive && "line-through text-muted-foreground",
                  )}
                >
                  {user.name}
                </h3>
                <p className="mt-0.5 truncate text-[13px] text-muted-foreground">
                  {user.position}
                </p>
                <div className="mt-1.5 flex items-center gap-1.5 text-[11px] text-muted-foreground">
                  <Building className="h-3.5 w-3.5 shrink-0" />
                  <span className="truncate">{user.department}</span>
                </div>
              </div>

              {showActions && (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-8 w-8 shrink-0 p-0 text-muted-foreground hover:text-foreground"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem
                      onClick={(e) => {
                        e.stopPropagation();
                        router.push(`/dashboard/users/${user.id}`);
                      }}
                    >
                      View Profile
                    </DropdownMenuItem>
                    {user.isActive && accessLevel.canEditUsers && (
                      <>
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEditUser(user);
                          }}
                          className="text-green-600 hover:text-green-700 hover:bg-green-50"
                        >
                          <UserIcon className="h-4 w-4 mr-2" />
                          Edit User
                        </DropdownMenuItem>
                        {canResetPassword(user) && (
                          <>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={(e) => {
                                e.stopPropagation();
                                handlePasswordReset(user);
                              }}
                              className="text-primary hover:text-primary hover:bg-primary/10"
                            >
                              <Key className="h-4 w-4 mr-2" />
                              Reset Password
                            </DropdownMenuItem>
                          </>
                        )}
                        {canMarkInactive(user) && (
                          <>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={(e) => {
                                e.stopPropagation();
                                handleRemoveUser(user);
                              }}
                              className="text-red-600 hover:text-red-700 hover:bg-red-50"
                            >
                              <UserX className="h-4 w-4 mr-2" />
                              Mark Inactive
                            </DropdownMenuItem>
                          </>
                        )}
                      </>
                    )}
                    {isInactive && (
                      <DropdownMenuItem
                        onClick={(e) => e.stopPropagation()}
                        className="text-muted-foreground cursor-not-allowed"
                        disabled
                      >
                        <AlertTriangle className="h-4 w-4 mr-2" />
                        User Inactive
                      </DropdownMenuItem>
                    )}
                    {canMarkActive(user) && (
                      <DropdownMenuItem
                        onClick={(e) => {
                          e.stopPropagation();
                          handleReactivateUser(user);
                        }}
                        className="text-green-600 hover:text-green-700 hover:bg-green-50"
                      >
                        <UserCheck className="h-4 w-4 mr-2" />
                        Mark Active
                      </DropdownMenuItem>
                    )}
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
          </div>
        </div>

        <div className="mt-3.5 grid grid-cols-2 gap-x-3 gap-y-2.5">
          {metaItems.map((item) => (
            <div key={item.label} className="min-w-0 flex items-start gap-2">
              <item.icon className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/80" />
              <div className="min-w-0">
                <p className="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
                  {item.label}
                </p>
                <p
                  className={cn(
                    "truncate text-[12px] text-foreground/85",
                    item.label === "Employee ID" && "tabular-nums text-[11px]",
                  )}
                  title={item.title ?? String(item.value)}
                >
                  {item.value}
                </p>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="border-t border-border px-4 py-3 space-y-3">
        <div className="flex flex-wrap items-center gap-1.5">
          <Badge
            variant="outline"
            className={cn(
              getRoleBadgeColor(user.role),
              "w-fit whitespace-nowrap px-2 py-0 text-[10px] font-medium",
              isInactive && "opacity-60",
            )}
          >
            <span className="mr-1 inline-flex scale-90">
              {getRoleIcon(user.role)}
            </span>
            {getRoleDisplayName(user.role)}
          </Badge>
          {user.joinDate && (
            <Badge
              variant="outline"
              className={cn(
                getEmploymentStatusBadgeColor(
                  calculateEmploymentStatus(user.joinDate).status,
                ),
                "w-fit whitespace-nowrap border px-2 py-0 text-[10px] font-medium",
                isInactive && "opacity-60",
              )}
            >
              {calculateEmploymentStatus(user.joinDate).label}
            </Badge>
          )}
          {user.joinDate && (
            <Badge
              variant="outline"
              className={cn(
                getGrowthEligibilityBadgeColor(
                  calculateGrowthEligibility(user.joinDate).isEligible,
                ),
                "w-fit whitespace-nowrap px-2 py-0 text-[10px] font-medium",
                isInactive && "opacity-60",
              )}
            >
              {calculateGrowthEligibility(user.joinDate).label}
            </Badge>
          )}
        </div>

        <div
          className={cn(
            "grid grid-cols-3 gap-2 divide-x divide-border rounded-lg border border-border bg-muted/20",
            isInactive && "opacity-60",
          )}
        >
          <div className="px-2 py-2 text-center">
            <div className="text-[13px] font-semibold tabular-nums text-primary">
              {actualProjects} / {expectedProjects}
            </div>
            <div className="mt-0.5 text-[10px] uppercase tracking-[0.06em] text-muted-foreground">
              Projects
            </div>
          </div>
          <div className="px-2 py-2 text-center">
            <div className="text-[13px] font-semibold tabular-nums text-emerald-600">
              {user._count.monthlyPerformance}
            </div>
            <div className="mt-0.5 text-[10px] uppercase tracking-[0.06em] text-muted-foreground">
              Reviews
            </div>
          </div>
          <div className="px-2 py-2 text-center">
            <div className="text-[13px] font-semibold tabular-nums text-foreground">
              {user._count.loggedHours}
            </div>
            <div className="mt-0.5 text-[10px] uppercase tracking-[0.06em] text-muted-foreground">
              Log entries
            </div>
          </div>
        </div>

        <div
          className={cn(
            "rounded-lg border border-border bg-muted/30 px-3 py-2.5",
            isInactive && "opacity-60",
          )}
        >
          {isInactive ? (
            <p className="text-center text-[13px] font-medium text-muted-foreground">
              Account inactive
            </p>
          ) : kpiLoading ? (
            <div className="space-y-2">
              <Skeleton className="mx-auto h-5 w-36" />
              <Skeleton className="mx-auto h-3 w-24" />
            </div>
          ) : kpiError ? (
            <p className="text-center text-[12px] text-destructive">
              KPI unavailable
            </p>
          ) : (
            <div className="flex items-end justify-between gap-3">
              <div className="min-w-0">
                <p className="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
                  Hours logged
                </p>
                <p className="mt-0.5 text-[15px] font-semibold tabular-nums tracking-tight text-foreground">
                  {loggedHours.toFixed(1)}h
                  {expectedHours > 0 && (
                    <span className="text-muted-foreground font-medium">
                      {" "}
                      / {expectedHours}h
                    </span>
                  )}
                </p>
              </div>
              {hoursPct !== null && (
                <div className="text-right">
                  <p
                    className={cn(
                      "text-[15px] font-semibold tabular-nums tracking-tight",
                      hoursPct >= 100 ? "text-emerald-600" : "text-primary",
                    )}
                  >
                    {hoursPct.toFixed(1)}%
                  </p>
                  <p className="text-[10px] text-muted-foreground">
                    of expected
                  </p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

// UserListView component for table format
interface UserListViewProps {
  users: ApiUser[];
  accessLevel: {
    canViewAll: boolean;
    canViewManagement: boolean;
    canCreateUsers: boolean;
    canEditUsers: boolean;
    canRemoveUsers?: boolean;
  };
  getInitials: (name: string) => string;
  getRoleBadgeColor: (role: string) => string;
  getRoleDisplayName: (role: string) => string;
  formatDate: (
    dateString: string,
    options?: { includeTime?: boolean; format?: "short" | "medium" | "long" },
  ) => string;
  handleEditUser: (user: ApiUser) => void;
  canResetPassword: (user: ApiUser) => boolean;
  canMarkInactive: (user: ApiUser) => boolean;
  handlePasswordReset: (user: ApiUser) => void;
  handleRemoveUser: (user: ApiUser) => void;
  canMarkActive: (user: ApiUser) => boolean;
  handleReactivateUser: (user: ApiUser) => void;
  kpis: Record<string, UserKpiSummary>;
  kpiLoading: boolean;
  kpiError: string | null;
}

function UserListView({
  users,
  accessLevel,
  getInitials,
  getRoleBadgeColor,
  getRoleDisplayName,
  formatDate,
  handleEditUser,
  canResetPassword,
  canMarkInactive,
  handlePasswordReset,
  handleRemoveUser,
  canMarkActive,
  handleReactivateUser,
  kpis,
  kpiLoading,
  kpiError,
}: UserListViewProps) {
  const router = useRouter();
  const canSeeInactiveStatus =
    accessLevel.canViewAll ||
    accessLevel.canViewManagement ||
    !!accessLevel.canRemoveUsers;
  const showActions =
    accessLevel.canEditUsers ||
    accessLevel.canViewAll ||
    !!accessLevel.canRemoveUsers;

  // Helper function to get expected project count based on department and role
  const getProjectExpectation = (
    department: string,
    role: string,
    techStack?: string,
  ) => {
    // Production department (original logic)
    if (department === "Production") {
      return techStack === "Backend" ? 12 : techStack === "Frontend" ? 6 : 9;
    }

    // Other departments based on role hierarchy
    switch (role) {
      case "SUPER_ADMIN":
      case "UPPER_MANAGEMENT":
        return department === "Engineering"
          ? 8
          : department === "Product"
            ? 10
            : department === "Design"
              ? 6
              : 4;

      case "MANAGER":
        return department === "Engineering"
          ? 6
          : department === "Product"
            ? 8
            : department === "Design"
              ? 5
              : department === "Marketing"
                ? 4
                : department === "Sales"
                  ? 5
                  : 3;

      case "UNIT_LEAD":
        return department === "Engineering"
          ? 4
          : department === "Product"
            ? 5
            : department === "Design"
              ? 4
              : department === "Marketing"
                ? 3
                : department === "Sales"
                  ? 4
                  : 2;

      case "MEMBER":
        return department === "Engineering"
          ? 3
          : department === "Product"
            ? 3
            : department === "Design"
              ? 2
              : department === "Marketing"
                ? 2
                : department === "Sales"
                  ? 3
                  : 1;

      default:
        return 2; // Default fallback
    }
  };

  // Component to display projects data
  const ProjectsCell = ({ user }: { user: ApiUser }) => {
    const kpi = kpis[user.id] || EMPTY_KPI;
    const expectedProjects = getProjectExpectation(
      user.department,
      user.role,
      user.techStack,
    );

    if (kpiLoading) {
      return (
        <div className="space-y-1.5">
          <Skeleton className="h-3.5 w-14" />
          <Skeleton className="h-3 w-12" />
        </div>
      );
    }

    if (kpiError) {
      return <div className="text-xs text-red-500">Error</div>;
    }

    return (
      <div className="text-sm">
        <div className="font-semibold text-primary">
          {kpi.actualProjects} / {expectedProjects}
        </div>
        <div className="text-xs text-muted-foreground">
          {user.department === "Production" && user.techStack
            ? user.techStack
            : "Projects"}
        </div>
        {user.projects && user.projects.length > 0 && (
          <div className="text-xs text-muted-foreground mt-1 max-w-[120px]">
            {user.projects.slice(0, 1).map((pm) => (
              <div
                key={pm.project.id}
                className="truncate"
                title={pm.project.name}
              >
                {pm.project.name}
              </div>
            ))}
            {user.projects.length > 1 && (
              <div className="text-muted-foreground">
                +{user.projects.length - 1} more
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  // Component to display logged hours data
  const LoggedHoursCell = ({ user }: { user: ApiUser }) => {
    const { loggedHours, expectedDays } = kpis[user.id] || EMPTY_KPI;

    if (kpiLoading) {
      return (
        <div className="space-y-1.5">
          <Skeleton className="h-3.5 w-16" />
          <Skeleton className="h-3 w-14" />
        </div>
      );
    }

    if (kpiError) {
      return <div className="text-xs text-red-500">Error</div>;
    }

    return (
      <div className="text-sm">
        <div className="font-semibold text-green-600">
          {loggedHours.toFixed(1)}h
        </div>
        {expectedDays > 0 ? (
          <div className="text-xs text-muted-foreground">
            {((loggedHours / (expectedDays * 8)) * 100).toFixed(1)}% of expected
          </div>
        ) : (
          <div className="text-xs text-muted-foreground">
            {user.totalLoggedHours.toFixed(1)}h total
          </div>
        )}
        <div className="text-xs text-muted-foreground">
          {user._count.loggedHours} entries
        </div>
      </div>
    );
  };

  return (
    <div className="rounded-xl border border-border bg-card overflow-hidden">
      <Table className="min-w-[1700px]">
        <TableHeader>
          <TableRow>
            <TableHead className="min-w-[200px]">User</TableHead>
            <TableHead className="min-w-[100px] whitespace-nowrap text-[10px]">
              Employee ID
            </TableHead>
            <TableHead className="min-w-[110px]">Role</TableHead>
            <TableHead className="min-w-[110px]">Status</TableHead>
            <TableHead className="min-w-[120px]">Eligibility</TableHead>
            <TableHead className="min-w-[120px]">Department</TableHead>
            <TableHead className="min-w-[180px]">Contact</TableHead>
            <TableHead className="min-w-[100px]">Joined</TableHead>
            <TableHead className="min-w-[140px]">Projects</TableHead>
            <TableHead className="min-w-[140px]">Logged Hours</TableHead>
            <TableHead className="min-w-[120px]">Performance</TableHead>
            <TableHead className="min-w-[80px] text-right">Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {users.map((user) => (
            <TableRow
              key={user.id}
              className={cn(
                "cursor-pointer",
                !user.isActive &&
                  canSeeInactiveStatus &&
                  "opacity-60 bg-red-50",
              )}
              onClick={() => router.push(`/dashboard/users/${user.id}`)}
            >
              <TableCell>
                <div className="flex items-center space-x-3">
                  <Avatar className="h-10 w-10">
                    <AvatarFallback className="font-semibold">
                      {getInitials(user.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <div
                      className={cn(
                        "font-medium text-foreground",
                        !user.isActive &&
                          canSeeInactiveStatus &&
                          "line-through",
                      )}
                    >
                      {user.name}
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {user.position}
                    </div>
                  </div>
                </div>
              </TableCell>

              <TableCell>
                <div className="text-xs text-muted-foreground tabular-nums">
                  {user.employeeId || "Not assigned"}
                </div>
              </TableCell>

              <TableCell>
                <div className="flex flex-col gap-1">
                  <Badge
                    variant="outline"
                    className={`${getRoleBadgeColor(user.role)} w-fit whitespace-nowrap px-2 py-0 text-[10px] font-medium`}
                  >
                    {getRoleDisplayName(user.role)}
                  </Badge>
                  {!user.isActive && canSeeInactiveStatus && (
                    <Badge
                      variant="destructive"
                      className="w-fit whitespace-nowrap px-2 py-0 text-[10px]"
                    >
                      Inactive
                    </Badge>
                  )}
                  <SsoBadge user={user} />
                </div>
              </TableCell>

              <TableCell>
                {user.joinDate ? (
                  <Badge
                    variant="outline"
                    className={`${getEmploymentStatusBadgeColor(calculateEmploymentStatus(user.joinDate).status)} w-fit whitespace-nowrap border px-2 py-0 text-[10px] font-medium`}
                  >
                    {calculateEmploymentStatus(user.joinDate).label}
                  </Badge>
                ) : (
                  <span className="text-xs text-muted-foreground">—</span>
                )}
              </TableCell>

              <TableCell>
                {user.joinDate ? (
                  <Badge
                    variant="outline"
                    className={`${getGrowthEligibilityBadgeColor(calculateGrowthEligibility(user.joinDate).isEligible)} w-fit whitespace-nowrap border px-2 py-0 text-[10px] font-medium`}
                  >
                    {calculateGrowthEligibility(user.joinDate).label}
                  </Badge>
                ) : (
                  <span className="text-xs text-muted-foreground">—</span>
                )}
              </TableCell>

              <TableCell>
                <div className="text-sm text-foreground">{user.department}</div>
                {user.department === "Production" && user.techStack && (
                  <div className="text-xs text-muted-foreground">
                    {user.techStack}
                  </div>
                )}
              </TableCell>

              <TableCell>
                <div className="text-sm text-foreground">{user.email}</div>
                {user.phone && (
                  <div className="text-xs text-muted-foreground">
                    {user.phone}
                  </div>
                )}
              </TableCell>

              <TableCell>
                <div className="text-sm text-foreground">
                  {formatDate(user.joinDate, { format: "short" })}
                </div>
              </TableCell>

              <TableCell>
                <ProjectsCell user={user} />
              </TableCell>

              <TableCell>
                <LoggedHoursCell user={user} />
              </TableCell>

              <TableCell>
                <div className="text-sm">
                  <div className="text-foreground">
                    {user._count.monthlyPerformance} reviews
                  </div>
                  <div className="text-muted-foreground">
                    {user._count.loggedHours} log entries
                  </div>
                </div>
              </TableCell>

              <TableCell className="text-right">
                {showActions && (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 w-8 p-0"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <MoreHorizontal className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem
                        onClick={(e) => {
                          e.stopPropagation();
                          router.push(`/dashboard/users/${user.id}`);
                        }}
                      >
                        View Profile
                      </DropdownMenuItem>
                      {user.isActive && accessLevel.canEditUsers && (
                        <>
                          <DropdownMenuItem
                            onClick={(e) => {
                              e.stopPropagation();
                              handleEditUser(user);
                            }}
                            className="text-green-600 hover:text-green-700 hover:bg-green-50"
                          >
                            <UserIcon className="h-4 w-4 mr-2" />
                            Edit User
                          </DropdownMenuItem>
                          {canResetPassword(user) && (
                            <>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handlePasswordReset(user);
                                }}
                                className="text-primary hover:text-primary hover:bg-primary/10"
                              >
                                <Key className="h-4 w-4 mr-2" />
                                Reset Password
                              </DropdownMenuItem>
                            </>
                          )}
                          {canMarkInactive(user) && (
                            <>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleRemoveUser(user);
                                }}
                                className="text-red-600 hover:text-red-700 hover:bg-red-50"
                              >
                                <UserX className="h-4 w-4 mr-2" />
                                Mark Inactive
                              </DropdownMenuItem>
                            </>
                          )}
                        </>
                      )}
                      {!user.isActive && canSeeInactiveStatus && (
                        <DropdownMenuItem
                          onClick={(e) => e.stopPropagation()}
                          className="text-muted-foreground cursor-not-allowed"
                          disabled
                        >
                          <AlertTriangle className="h-4 w-4 mr-2" />
                          User Inactive
                        </DropdownMenuItem>
                      )}
                      {canMarkActive(user) && (
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            handleReactivateUser(user);
                          }}
                          className="text-green-600 hover:text-green-700 hover:bg-green-50"
                        >
                          <UserCheck className="h-4 w-4 mr-2" />
                          Mark Active
                        </DropdownMenuItem>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                )}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}

export default function UsersPage() {
  const { data: session, status } = useSession();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedRole, setSelectedRole] = useState<string>("all");
  const [selectedDepartment, setSelectedDepartment] = useState<string>("all");
  const [selectedDesignation, setSelectedDesignation] = useState<string>("all");
  const [selectedManager, setSelectedManager] = useState<string>("all");
  const [selectedEmploymentStatus, setSelectedEmploymentStatus] =
    useState<string>("all");
  const [selectedGrowthEligibility, setSelectedGrowthEligibility] =
    useState<string>("all");
  const [selectedTechStack, setSelectedTechStack] = useState<string>("all");
  const [activeStatusFilter, setActiveStatusFilter] =
    useState<string>("active"); // 'active', 'inactive', 'all' (inactive listed last)
  const [viewMode, setViewMode] = useState<"card" | "list">("list");
  const PAGE_SIZE = 10;
  const [currentPage, setCurrentPage] = useState(1);
  const [totalUsers, setTotalUsers] = useState(0);
  const [summary, setSummary] = useState<UsersSummary | null>(null);
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const filtersLoaded = useRef(false);

  // KPI date range filter — defaults to Jan 1 of current year → today
  const todayStr = new Date().toISOString().split("T")[0];
  const yearStartStr = `${new Date().getFullYear()}-01-01`;
  const [kpiDateFrom, setKpiDateFrom] = useState<string>(yearStartStr);
  const [kpiDateTo, setKpiDateTo] = useState<string>(todayStr);
  const [users, setUsers] = useState<ApiUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [accessLevel, setAccessLevel] = useState({
    canViewAll: false,
    canViewManagement: false,
    canCreateUsers: false,
    canEditUsers: false,
    canRemoveUsers: false,
  });
  const [currentUserRole, setCurrentUserRole] = useState<string>("");
  const [filterOptions, setFilterOptions] = useState<{
    departments: string[];
    designations: string[];
    techStacks: string[];
    managers: { id: string; name: string }[];
    teamLeads: { id: string; name: string }[];
  }>({
    departments: [],
    designations: [],
    techStacks: [],
    managers: [],
    teamLeads: [],
  });

  // Password reset modal state
  const [isPasswordResetModalOpen, setIsPasswordResetModalOpen] =
    useState(false);
  const [selectedUserForReset, setSelectedUserForReset] =
    useState<ApiUser | null>(null);

  // Edit user modal state
  const [isEditUserModalOpen, setIsEditUserModalOpen] = useState(false);
  const [selectedUserForEdit, setSelectedUserForEdit] =
    useState<ApiUser | null>(null);

  // Remove user confirmation dialog state
  const [isRemoveUserDialogOpen, setIsRemoveUserDialogOpen] = useState(false);
  const [selectedUserForRemoval, setSelectedUserForRemoval] =
    useState<ApiUser | null>(null);
  const [isRemovingUser, setIsRemovingUser] = useState(false);

  // Reactivate (mark active) confirmation dialog state
  const [selectedUserForReactivation, setSelectedUserForReactivation] =
    useState<ApiUser | null>(null);
  const [isReactivatingUser, setIsReactivatingUser] = useState(false);

  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(searchTerm.trim()), 300);
    return () => clearTimeout(t);
  }, [searchTerm]);

  useEffect(() => {
    setCurrentPage(1);
  }, [
    debouncedSearch,
    selectedRole,
    selectedDepartment,
    selectedDesignation,
    selectedManager,
    selectedTechStack,
    activeStatusFilter,
  ]);

  const usersListParams = useMemo(
    () => ({
      ...(debouncedSearch ? { search: debouncedSearch } : {}),
      ...(selectedRole !== "all" ? { role: selectedRole } : {}),
      ...(selectedDepartment !== "all" ? { department: selectedDepartment } : {}),
      ...(selectedDesignation !== "all" ? { position: selectedDesignation } : {}),
      ...(selectedManager !== "all" ? { managerId: selectedManager } : {}),
      ...(selectedTechStack !== "all" ? { techStack: selectedTechStack } : {}),
      ...(activeStatusFilter === "active"
        ? { isActive: "true" }
        : activeStatusFilter === "inactive"
          ? { isActive: "false" }
          : activeStatusFilter === "all"
            ? { isActive: "all" }
            : {}),
    }),
    [
      debouncedSearch,
      selectedRole,
      selectedDepartment,
      selectedDesignation,
      selectedManager,
      selectedTechStack,
      activeStatusFilter,
    ],
  );

  const fetchUsers = useCallback(
    async (page = currentPage) => {
      try {
        setLoading(true);
        const data: UsersResponse & {
          filterOptions?: {
            departments: string[];
            designations: string[];
            techStacks: string[];
            managers: { id: string; name: string }[];
            teamLeads?: { id: string; name: string }[];
          };
        } = await apiCall(
          api.endpoints.getUsers.initiate({
            page,
            limit: PAGE_SIZE,
            ...(!filtersLoaded.current || page === 1
              ? { includeFilters: "1" }
              : {}),
            ...usersListParams,
          }),
        );
        setUsers(data.users);
        setTotalUsers(data.pagination?.total ?? data.users.length);
        setSummary(data.summary ?? null);
        setCurrentUserRole(data.currentUserRole);
        // Super Admin always gets unrestricted user-management actions
        const isSuperAdmin =
          data.currentUserRole === "SUPER_ADMIN" ||
          session?.user?.role === "SUPER_ADMIN";
        setAccessLevel({
          canViewAll: isSuperAdmin || !!data.accessLevel?.canViewAll,
          canViewManagement:
            isSuperAdmin || !!data.accessLevel?.canViewManagement,
          canCreateUsers: isSuperAdmin || !!data.accessLevel?.canCreateUsers,
          canEditUsers: isSuperAdmin || !!data.accessLevel?.canEditUsers,
          canRemoveUsers: isSuperAdmin || !!data.accessLevel?.canRemoveUsers,
        });
        if (data.filterOptions) {
          setFilterOptions({
            departments: data.filterOptions.departments || [],
            designations: data.filterOptions.designations || [],
            techStacks: data.filterOptions.techStacks || [],
            managers: data.filterOptions.managers || [],
            teamLeads: data.filterOptions.teamLeads || [],
          });
          filtersLoaded.current = true;
        }
      } catch (error) {
        console.error("Error fetching users:", error);
        toast({
          title: "Error",
          description: "Failed to load users. Please try again.",
          variant: "destructive",
        });
      } finally {
        setLoading(false);
      }
    },
    [currentPage, usersListParams, session?.user?.role],
  );

  // Ensure Super Admin permissions are applied even before/without API accessLevel
  useEffect(() => {
    if (session?.user?.role !== "SUPER_ADMIN") return;
    setAccessLevel((prev) => ({
      ...prev,
      canViewAll: true,
      canViewManagement: true,
      canCreateUsers: true,
      canEditUsers: true,
      canRemoveUsers: true,
    }));
    setCurrentUserRole((prev) => prev || "SUPER_ADMIN");
  }, [session?.user?.role]);

  useEffect(() => {
    if (status === "authenticated") {
      fetchUsers(currentPage);
    }
  }, [status, currentPage, fetchUsers]);

  // Super admins can mark anyone inactive; managers only active unit leads / members
  // in their list (the API enforces the same scope).
  const canMarkInactive = (targetUser: ApiUser): boolean => {
    if (!accessLevel.canRemoveUsers || !targetUser.isActive) return false;
    if (targetUser.id === session?.user?.id) return false;
    if (currentUserRole === "SUPER_ADMIN" || session?.user?.role === "SUPER_ADMIN")
      return true;
    return targetUser.role === "UNIT_LEAD" || targetUser.role === "MEMBER";
  };

  // Same rules as marking inactive, for users that are currently inactive.
  const canMarkActive = (targetUser: ApiUser): boolean =>
    !targetUser.isActive && canMarkInactive({ ...targetUser, isActive: true });

  // Check if current user can reset password for the target user
  const canResetPassword = (targetUser: ApiUser): boolean => {
    if (!session?.user) return false;

    const currentUserRole = session.user.role;
    const currentUserId = session.user.id;
    const currentUserDepartment = session.user.department;
    const currentUserPosition = session.user.position;

    // Check if user has executive/HR designation that grants full access
    const hasExecutiveAccess = !!(
      currentUserPosition && ["CEO", "COO"].includes(currentUserPosition)
    );
    const hasHRAccess = !!(
      currentUserPosition &&
      (currentUserPosition.includes("HR") ||
        currentUserPosition.includes("Human Resources") ||
        currentUserPosition === "VP Human Resources" ||
        currentUserPosition === "HR Manager" ||
        currentUserPosition === "HR Business Partner" ||
        currentUserPosition === "Talent Acquisition Manager")
    );

    // Users cannot reset their own password through this interface
    if (targetUser.id === currentUserId) return false;

    switch (currentUserRole) {
      case "SUPER_ADMIN":
        return true;

      case "UPPER_MANAGEMENT":
        // Can reset any password except super admin, or if they have executive/HR access
        return (
          targetUser.role !== "SUPER_ADMIN" || hasExecutiveAccess || hasHRAccess
        );

      case "MANAGER":
        // Can reset passwords for unit leads and members in their department, or if they have executive/HR access
        return (
          (targetUser.department === currentUserDepartment &&
            ["UNIT_LEAD", "MEMBER"].includes(targetUser.role)) ||
          hasExecutiveAccess ||
          hasHRAccess
        );

      case "UNIT_LEAD":
        // Can reset passwords for members who report to them directly, or if they have executive/HR access
        return (
          (targetUser.role === "MEMBER" &&
            (targetUser.managerId === currentUserId ||
              (targetUser.department === currentUserDepartment &&
                !targetUser.managerId))) ||
          hasExecutiveAccess ||
          hasHRAccess
        );

      case "MEMBER":
        // Members can only reset passwords if they have executive/HR access
        return hasExecutiveAccess || hasHRAccess;

      default:
        return false;
    }
  };

  // Handle opening password reset modal
  const handlePasswordReset = (user: ApiUser) => {
    setSelectedUserForReset(user);
    setIsPasswordResetModalOpen(true);
  };

  // Handle closing password reset modal
  const handleClosePasswordResetModal = () => {
    setIsPasswordResetModalOpen(false);
    setSelectedUserForReset(null);
  };

  // Handle opening edit user modal
  const handleEditUser = async (user: ApiUser) => {
    // Open immediately with list data, then hydrate with a light edit payload.
    // Avoids the heavy GET (performance graphs etc.) that used to fan out
    // parallel session cookie rewrites and log users out.
    setSelectedUserForEdit(user);
    setIsEditUserModalOpen(true);

    try {
      const freshUserData = await apiCall<ApiUser>(
        api.endpoints.getUser.initiate({ id: user.id, for: "edit" }),
      );
      setSelectedUserForEdit(freshUserData);
    } catch (error) {
      console.error("Error fetching fresh user data for edit:", error);
    }
  };

  // Handle closing edit user modal
  const handleCloseEditUserModal = () => {
    setIsEditUserModalOpen(false);
    setSelectedUserForEdit(null);
  };

  // Handle user updated
  const handleUserUpdated = () => {
    fetchUsers(); // Refresh the users list
  };

  // Handle opening remove user confirmation dialog
  const handleRemoveUser = (user: ApiUser) => {
    setSelectedUserForRemoval(user);
    setIsRemoveUserDialogOpen(true);
  };

  // Handle closing remove user confirmation dialog
  const handleCloseRemoveUserDialog = () => {
    setIsRemoveUserDialogOpen(false);
    setSelectedUserForRemoval(null);
  };

  const handleReactivateUser = (user: ApiUser) => {
    setSelectedUserForReactivation(user);
  };

  const handleConfirmReactivateUser = async () => {
    if (!selectedUserForReactivation) return;

    setIsReactivatingUser(true);
    try {
      await apiCall(
        api.endpoints.reactivateUser.initiate(selectedUserForReactivation.id),
      );

      toast({
        title: "User Marked Active",
        description: `${selectedUserForReactivation.name} is active again and can log in.`,
        variant: "default",
      });

      fetchUsers();
    } catch (error) {
      console.error("Error reactivating user:", error);
      toast({
        title: "Error",
        description:
          error instanceof Error
            ? error.message
            : "Failed to mark user active. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsReactivatingUser(false);
      setSelectedUserForReactivation(null);
    }
  };

  // Handle actual user removal
  const handleConfirmRemoveUser = async () => {
    if (!selectedUserForRemoval) return;

    setIsRemovingUser(true);
    try {
      await apiCall(
        api.endpoints.deleteUser.initiate(selectedUserForRemoval.id),
      );

      toast({
        title: "User Marked Inactive",
        description: `${selectedUserForRemoval.name} is now inactive and can no longer log in.`,
        variant: "default",
      });

      // Refresh the users list
      fetchUsers();
    } catch (error) {
      console.error("Error removing user:", error);
      toast({
        title: "Error",
        description:
          error instanceof Error
            ? error.message
            : "Failed to mark user inactive. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsRemovingUser(false);
      handleCloseRemoveUserDialog();
    }
  };

  // Server already applies search/role/department/position/manager/techStack/isActive.
  // Keep only joinDate-derived filters and self-exclusion client-side on the current page.
  const filteredUsers = users.filter((user) => {
    const matchesEmploymentStatus =
      selectedEmploymentStatus === "all" ||
      (user.joinDate &&
        calculateEmploymentStatus(user.joinDate).status ===
          selectedEmploymentStatus);

    const matchesGrowthEligibility =
      selectedGrowthEligibility === "all" ||
      (user.joinDate &&
        (calculateGrowthEligibility(user.joinDate).isEligible
          ? "eligible"
          : "not-eligible") === selectedGrowthEligibility);

    const isCurrentUser = user.id === session?.user?.id;
    const shouldExcludeCurrentUser =
      isCurrentUser &&
      selectedManager === "all" &&
      (currentUserRole === "MANAGER" ||
        currentUserRole === "UNIT_LEAD" ||
        currentUserRole === "UPPER_MANAGEMENT");

    return (
      matchesEmploymentStatus &&
      matchesGrowthEligibility &&
      !shouldExcludeCurrentUser
    );
  });

  const applyExportClientFilters = useCallback(
    (list: UsersPageExportPerson[]) =>
      list.filter((user) => {
        const matchesEmploymentStatus =
          selectedEmploymentStatus === "all" ||
          (user.joinDate &&
            calculateEmploymentStatus(user.joinDate).status ===
              selectedEmploymentStatus);
        const matchesGrowthEligibility =
          selectedGrowthEligibility === "all" ||
          (user.joinDate &&
            (calculateGrowthEligibility(user.joinDate).isEligible
              ? "eligible"
              : "not-eligible") === selectedGrowthEligibility);
        const isCurrentUser = user.id === session?.user?.id;
        const shouldExcludeCurrentUser =
          isCurrentUser &&
          selectedManager === "all" &&
          (currentUserRole === "MANAGER" ||
            currentUserRole === "UNIT_LEAD" ||
            currentUserRole === "UPPER_MANAGEMENT");
        return (
          matchesEmploymentStatus &&
          matchesGrowthEligibility &&
          !shouldExcludeCurrentUser
        );
      }),
    [
      selectedEmploymentStatus,
      selectedGrowthEligibility,
      selectedManager,
      session?.user?.id,
      currentUserRole,
    ],
  );

  const visibleUserIds = useMemo(
    () => filteredUsers.map((u) => u.id),
    [filteredUsers],
  );
  const {
    kpis: kpiMap,
    loading: kpiLoading,
    error: kpiError,
  } = useUsersKpiBatch(visibleUserIds, kpiDateFrom, kpiDateTo);

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase();
  };

  const getAvailableRoles = () => {
    const roleOptions = [];

    if (accessLevel.canViewAll) {
      roleOptions.push(
        { value: "SUPER_ADMIN", label: "Super Admin" },
        { value: "UPPER_MANAGEMENT", label: "Top Management" },
        { value: "MANAGER", label: "Manager" },
        { value: "UNIT_LEAD", label: "Unit Lead" },
        { value: "MEMBER", label: "Member" },
      );
    } else if (accessLevel.canViewManagement) {
      roleOptions.push(
        { value: "UPPER_MANAGEMENT", label: "Top Management" },
        { value: "MANAGER", label: "Manager" },
        { value: "UNIT_LEAD", label: "Unit Lead" },
        { value: "MEMBER", label: "Member" },
      );
    } else if (currentUserRole === "MANAGER") {
      roleOptions.push(
        { value: "UNIT_LEAD", label: "Unit Lead" },
        { value: "MEMBER", label: "Member" },
      );
    } else if (currentUserRole === "UNIT_LEAD") {
      roleOptions.push(
        { value: "UNIT_LEAD", label: "Unit Lead" },
        { value: "MEMBER", label: "Member" },
      );
    }

    return roleOptions;
  };

  const getAvailableDepartments = () => filterOptions.departments;

  const getAvailableDesignations = () => filterOptions.designations;

  const getAvailableManagers = () =>
    filterOptions.managers.map((manager) => ({
      value: manager.id,
      label: manager.name,
    }));

  const getAvailableTeamLeads = () =>
    filterOptions.teamLeads.map((lead) => ({
      value: lead.id,
      label: lead.name,
    }));

  // Super Admin / Top Management / org-wide viewers: Managers filter (role = MANAGER).
  // Manager / Unit Lead: never show Managers — show Team Leads in managed scope instead.
  const isScopedPeopleManager =
    currentUserRole === "MANAGER" || currentUserRole === "UNIT_LEAD";
  const showManagersFilter =
    !isScopedPeopleManager &&
    (currentUserRole === "SUPER_ADMIN" ||
      currentUserRole === "UPPER_MANAGEMENT" ||
      accessLevel.canViewAll);
  const showTeamLeadsFilter = isScopedPeopleManager;

  const getAvailableTechStacks = (): string[] => filterOptions.techStacks;

  if (status === "loading" || (loading && users.length === 0)) {
    return <UsersPageSkeleton />;
  }

  if (status === "unauthenticated") {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <Shield className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">
            Access Denied
          </h3>
          <p className="text-muted-foreground">Please sign in to view users.</p>
        </div>
      </div>
    );
  }

  const hasActiveFilters =
    selectedRole !== "all" ||
    selectedDepartment !== "all" ||
    selectedDesignation !== "all" ||
    selectedManager !== "all" ||
    selectedEmploymentStatus !== "all" ||
    selectedGrowthEligibility !== "all" ||
    selectedTechStack !== "all" ||
    ((accessLevel.canViewAll ||
      accessLevel.canViewManagement ||
      accessLevel.canRemoveUsers) &&
      activeStatusFilter !== "active");

  const usersExportLabel = (() => {
    if (selectedManager !== "all") {
      const leadName = (
        showTeamLeadsFilter ? getAvailableTeamLeads() : getAvailableManagers()
      ).find((m) => m.value === selectedManager)?.label;
      return leadName ? `Team - ${leadName}` : "Selected team";
    }
    if (hasActiveFilters) return "Filtered users";
    return "All users";
  })();

  const activeFilterCount = [
    selectedRole !== "all",
    selectedDepartment !== "all",
    selectedDesignation !== "all",
    selectedManager !== "all",
    selectedEmploymentStatus !== "all",
    selectedGrowthEligibility !== "all",
    selectedTechStack !== "all",
    (accessLevel.canViewAll ||
      accessLevel.canViewManagement ||
      accessLevel.canRemoveUsers) &&
      activeStatusFilter !== "active",
  ].filter(Boolean).length;

  const clearAllFilters = () => {
    setSelectedRole("all");
    setSelectedDepartment("all");
    setSelectedDesignation("all");
    setSelectedManager("all");
    setSelectedEmploymentStatus("all");
    setSelectedGrowthEligibility("all");
    setSelectedTechStack("all");
    setActiveStatusFilter("active");
  };

  const filterCategories: UsersFilterCategory[] = (() => {
    const categories: UsersFilterCategory[] = [
      {
        id: "role",
        label: "Role",
        value: selectedRole,
        onChange: setSelectedRole,
        options: [
          { value: "all", label: "All roles" },
          ...getAvailableRoles().map((role) => ({
            value: role.value,
            label: role.label,
          })),
        ],
      },
      {
        id: "department",
        label: "Department",
        value: selectedDepartment,
        onChange: setSelectedDepartment,
        options: [
          { value: "all", label: "All departments" },
          ...getAvailableDepartments().map((department) => ({
            value: department,
            label: department,
          })),
        ],
      },
      {
        id: "designation",
        label: "Designation",
        value: selectedDesignation,
        onChange: setSelectedDesignation,
        options: [
          { value: "all", label: "All designations" },
          ...getAvailableDesignations().map((designation) => ({
            value: designation,
            label: designation,
          })),
        ],
      },
    ];

    if (showManagersFilter) {
      categories.push({
        id: "manager",
        label: "Manager",
        value: selectedManager,
        onChange: setSelectedManager,
        searchable: true,
        options: [
          { value: "all", label: "All managers" },
          ...getAvailableManagers().map((manager) => ({
            value: manager.value,
            label: manager.label,
          })),
        ],
      });
    }

    if (showTeamLeadsFilter) {
      categories.push({
        id: "teamLead",
        label: "Team lead",
        value: selectedManager,
        onChange: setSelectedManager,
        searchable: true,
        options: [
          { value: "all", label: "All team leads" },
          ...getAvailableTeamLeads().map((lead) => ({
            value: lead.value,
            label: lead.label,
          })),
        ],
      });
    }

    categories.push(
      {
        id: "employment",
        label: "Employment status",
        value: selectedEmploymentStatus,
        onChange: setSelectedEmploymentStatus,
        options: [
          { value: "all", label: "All statuses" },
          { value: "probation", label: "Probation" },
          { value: "permanent", label: "Permanent" },
        ],
      },
      {
        id: "growth",
        label: "Growth status",
        value: selectedGrowthEligibility,
        onChange: setSelectedGrowthEligibility,
        options: [
          { value: "all", label: "All growth statuses" },
          { value: "eligible", label: "Eligible" },
          { value: "not-eligible", label: "Not eligible" },
        ],
      },
    );

    if (getAvailableTechStacks().length > 0) {
      categories.push({
        id: "techStack",
        label: "Tech stack",
        value: selectedTechStack,
        onChange: setSelectedTechStack,
        options: [
          { value: "all", label: "All tech stacks" },
          ...getAvailableTechStacks().map((techStack) => ({
            value: techStack,
            label: techStack,
          })),
        ],
      });
    }

    if (
      accessLevel.canViewAll ||
      accessLevel.canViewManagement ||
      accessLevel.canRemoveUsers
    ) {
      categories.push({
        id: "activeStatus",
        label: "Account status",
        value: activeStatusFilter,
        defaultValue: "active",
        onChange: setActiveStatusFilter,
        options: [
          { value: "active", label: "Active users" },
          { value: "inactive", label: "Inactive users" },
          { value: "all", label: "All users" },
        ],
      });
    }

    return categories;
  })();

  const isPeopleManager =
    currentUserRole === "MANAGER" || currentUserRole === "UNIT_LEAD";

  const overviewMetrics: {
    label: string;
    value: number;
    icon: typeof Users;
  }[] = isPeopleManager
    ? [
        {
          label: "Workforce",
          value: summary?.workforce ?? Math.max(0, totalUsers - 1),
          icon: Users,
        },
        {
          label: "Departments",
          value: summary?.departments ?? filterOptions.departments.length,
          icon: Building,
        },
        {
          label: "Team leads",
          value: summary?.teamLeads ?? 0,
          icon: Network,
        },
        {
          label: "Active",
          value: summary?.active ?? summary?.workforce ?? 0,
          icon: UserCheck,
        },
      ]
    : [
        {
          label: "Total",
          value: summary?.total ?? totalUsers,
          icon: Users,
        },
        {
          label: "Active",
          value: summary?.active ?? 0,
          icon: UserCheck,
        },
        {
          label: "Departments",
          value: summary?.departments ?? filterOptions.departments.length,
          icon: Building,
        },
        {
          label: "Team leads",
          value: summary?.unitLeads ?? 0,
          icon: Network,
        },
      ];

  const roleStats: { label: string; value: number; tone: string }[] = [];
  if (
    currentUserRole === "SUPER_ADMIN" ||
    currentUserRole === "UPPER_MANAGEMENT"
  ) {
    if (currentUserRole === "SUPER_ADMIN") {
      roleStats.push({
        label: "Super Admins",
        value: summary?.superAdmins ?? 0,
        tone: "text-red-600 dark:text-red-400",
      });
    }
    roleStats.push(
      {
        label: "Top Management",
        value: summary?.upperManagement ?? 0,
        tone: "text-primary",
      },
      {
        label: "Managers",
        value: summary?.managers ?? 0,
        tone: "text-emerald-600 dark:text-emerald-400",
      },
      {
        label: "Unit Leads",
        value: summary?.unitLeads ?? 0,
        tone: "text-amber-600 dark:text-amber-400",
      },
    );
  }
  // People managers: skip Managers / Team leads here (Team leads is already in
  // the overview cards; peer Managers aren't actionable). Keep IC count + activity.
  roleStats.push(
    {
      label: "Members",
      value: summary?.members ?? 0,
      tone: "text-foreground",
    },
    {
      label: "Log entries",
      value: summary?.logEntries ?? 0,
      tone: "text-primary",
    },
    {
      label: "Hours logged",
      value: summary?.hoursLogged ?? 0,
      tone: "text-amber-600 dark:text-amber-400",
    },
  );

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div className="space-y-0.5 min-w-0">
          <p className="text-sm text-muted-foreground">
            {currentUserRole === "SUPER_ADMIN" && "Manage all system users"}
            {currentUserRole === "UPPER_MANAGEMENT" &&
              "Manage organizational users"}
            {currentUserRole === "MANAGER" &&
              "Manage your teams across departments and units"}
            {currentUserRole === "UNIT_LEAD" &&
              "Overview of everyone in your reporting tree"}
          </p>
          <p className="text-xs text-muted-foreground tabular-nums">
            {isPeopleManager
              ? `${summary?.workforce ?? Math.max(0, totalUsers - 1)} people in your managed scope`
              : `${totalUsers} people match your filters`}
          </p>
        </div>
        {accessLevel.canCreateUsers && (
          <Link href="/dashboard/users/create">
            <Button size="sm" className="gap-1.5">
              <UserPlus className="h-4 w-4" />
              Add user
            </Button>
          </Link>
        )}
      </div>

      {/* Overview: primary metrics + role/hours breakdown */}
      <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
        <div className="grid grid-cols-2 lg:grid-cols-4 divide-x divide-y lg:divide-y-0 divide-border">
          {overviewMetrics.map((m) => (
            <div key={m.label} className="px-4 py-3 min-w-0">
              <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
                <m.icon className="h-3 w-3 text-primary" />
                {m.label}
              </div>
              <p className="mt-0.5 text-xl font-semibold tracking-tight tabular-nums text-foreground">
                {m.value}
              </p>
            </div>
          ))}
        </div>

        <div className="border-t border-border bg-muted/20 px-4 py-2.5">
          <div className="flex items-center gap-2 mb-2">
            <Users className="h-3.5 w-3.5 text-primary" />
            <span className="text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground">
              Breakdown
            </span>
          </div>
          <div className="flex flex-wrap gap-x-5 gap-y-2">
            {roleStats.map((stat) => (
              <div
                key={stat.label}
                className="flex items-baseline gap-1.5 min-w-0"
              >
                <span
                  className={cn(
                    "text-sm font-semibold tabular-nums",
                    stat.tone,
                  )}
                >
                  {stat.label === "Hours logged"
                    ? `${stat.value}h`
                    : stat.value}
                </span>
                <span className="text-[11px] text-muted-foreground whitespace-nowrap">
                  {stat.label}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Search & filters */}
      <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
        <div className="p-3 sm:p-4 space-y-3">
          <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2.5">
            <div className="relative w-full max-w-xs min-w-[180px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
              <Input
                placeholder="Search users by name, email, or position..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="h-9 pl-9"
              />
            </div>

            <div className="flex flex-wrap items-center gap-2 shrink-0">
              <Calendar className="h-4 w-4 text-muted-foreground shrink-0 hidden sm:block" />
              <span className="hidden md:inline text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground whitespace-nowrap">
                KPI period
              </span>
              <DatePicker
                value={kpiDateFrom}
                max={kpiDateTo}
                onChange={setKpiDateFrom}
                buttonClassName="h-9 w-[128px] px-2 text-sm"
                title="From date"
              />
              <span className="text-xs text-muted-foreground">to</span>
              <DatePicker
                value={kpiDateTo}
                min={kpiDateFrom}
                max={new Date().toISOString().split("T")[0]}
                onChange={setKpiDateTo}
                buttonClassName="h-9 w-[128px] px-2 text-sm"
                title="To date"
              />
              {(kpiDateFrom !== yearStartStr || kpiDateTo !== todayStr) && (
                <button
                  onClick={() => {
                    setKpiDateFrom(yearStartStr);
                    setKpiDateTo(todayStr);
                  }}
                  className="text-xs text-primary hover:underline whitespace-nowrap"
                  title="Reset to current year"
                >
                  Reset
                </button>
              )}
              <ToggleGroup
                type="single"
                variant="outline"
                size="sm"
                value={viewMode}
                onValueChange={(value) =>
                  value && setViewMode(value as "card" | "list")
                }
                className="justify-start gap-0 rounded-md border border-input p-0"
              >
                <ToggleGroupItem
                  value="card"
                  aria-label="Card view"
                  className="h-9 w-9 rounded-none rounded-l-md border-0 px-0 data-[state=on]:bg-primary/10 data-[state=on]:text-primary"
                >
                  <Grid3X3 className="h-4 w-4" />
                </ToggleGroupItem>
                <ToggleGroupItem
                  value="list"
                  aria-label="List view"
                  className="h-9 w-9 rounded-none rounded-r-md border-0 border-l border-input px-0 data-[state=on]:bg-primary/10 data-[state=on]:text-primary"
                >
                  <List className="h-4 w-4" />
                </ToggleGroupItem>
              </ToggleGroup>
              <UsersPageExportMenu
                listParams={usersListParams}
                dateFrom={kpiDateFrom}
                dateTo={kpiDateTo}
                filterLabel={usersExportLabel}
                applyClientFilters={applyExportClientFilters}
              />
              <UsersFilterPanel
                categories={filterCategories}
                activeCount={activeFilterCount}
                onClearAll={clearAllFilters}
              />
            </div>
          </div>

          {hasActiveFilters && (
            <div className="flex flex-wrap items-center gap-2 pt-1">
              <span className="text-[11px] text-muted-foreground">Active:</span>
              {selectedRole !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Role: {getRoleDisplayName(selectedRole)}
                </Badge>
              )}
              {selectedDepartment !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Dept: {selectedDepartment}
                </Badge>
              )}
              {selectedDesignation !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Position: {selectedDesignation}
                </Badge>
              )}
              {selectedManager !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  {showTeamLeadsFilter ? "Team Lead" : "Manager"}:{" "}
                  {
                    (showTeamLeadsFilter
                      ? getAvailableTeamLeads()
                      : getAvailableManagers()
                    ).find((m) => m.value === selectedManager)?.label
                  }
                </Badge>
              )}
              {selectedEmploymentStatus !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Status:{" "}
                  {selectedEmploymentStatus === "probation"
                    ? "Probation"
                    : "Permanent"}
                </Badge>
              )}
              {selectedGrowthEligibility !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Growth:{" "}
                  {selectedGrowthEligibility === "eligible"
                    ? "Eligible"
                    : "Not Eligible"}
                </Badge>
              )}
              {selectedTechStack !== "all" && (
                <Badge variant="secondary" className="text-[10px] font-medium">
                  Tech: {selectedTechStack}
                </Badge>
              )}
              {(accessLevel.canViewAll ||
                accessLevel.canViewManagement ||
                accessLevel.canRemoveUsers) &&
                activeStatusFilter !== "active" && (
                  <Badge
                    variant="secondary"
                    className="text-[10px] font-medium"
                  >
                    {activeStatusFilter === "inactive"
                      ? "Inactive Only"
                      : "All Users"}
                  </Badge>
                )}
              <Button
                variant="ghost"
                size="sm"
                onClick={clearAllFilters}
                className="text-xs text-primary hover:text-primary h-6 px-2"
              >
                Clear all
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* Users Display - Card or List View */}
      <div className="relative min-h-[12rem]">
        {loading && (
          <div className="absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/60 backdrop-blur-[1px]">
            <div className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2.5 shadow-sm">
              <AppSpinner className="h-4 w-4" />
              <span className="text-sm text-muted-foreground">
                Updating users…
              </span>
            </div>
          </div>
        )}

        <div
          className={cn(
            "space-y-5 transition-opacity duration-200",
            loading && "pointer-events-none opacity-50",
          )}
        >
          {viewMode === "card" ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredUsers.map((user) => (
                <UserCardWithKPI
                  key={user.id}
                  user={user}
                  accessLevel={accessLevel}
                  getInitials={getInitials}
                  getRoleBadgeColor={getRoleBadgeColor}
                  getRoleIcon={getRoleIcon}
                  getRoleDisplayName={getRoleDisplayName}
                  handleEditUser={handleEditUser}
                  canResetPassword={canResetPassword}
                  canMarkInactive={canMarkInactive}
                  handlePasswordReset={handlePasswordReset}
                  handleRemoveUser={handleRemoveUser}
                  canMarkActive={canMarkActive}
                  handleReactivateUser={handleReactivateUser}
                  formatDate={formatDate}
                  kpi={kpiMap[user.id] || EMPTY_KPI}
                  kpiLoading={kpiLoading}
                  kpiError={kpiError}
                />
              ))}
            </div>
          ) : (
            <UserListView
              users={filteredUsers}
              accessLevel={accessLevel}
              getInitials={getInitials}
              getRoleBadgeColor={getRoleBadgeColor}
              getRoleDisplayName={getRoleDisplayName}
              formatDate={formatDate}
              handleEditUser={handleEditUser}
              canResetPassword={canResetPassword}
              canMarkInactive={canMarkInactive}
              handlePasswordReset={handlePasswordReset}
              handleRemoveUser={handleRemoveUser}
              canMarkActive={canMarkActive}
              handleReactivateUser={handleReactivateUser}
              kpis={kpiMap}
              kpiLoading={kpiLoading}
              kpiError={kpiError}
            />
          )}

          {totalUsers > 0 && (
            <div className="rounded-xl border border-border bg-card overflow-hidden">
              <TablePagination
                currentPage={currentPage}
                totalItems={totalUsers}
                pageSize={PAGE_SIZE}
                onPageChange={setCurrentPage}
                itemLabel="users"
              />
            </div>
          )}

          {filteredUsers.length === 0 && !loading && (
            <Card className="p-12 text-center">
              <Users className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-foreground mb-2">
                No users found
              </h3>
              <p className="text-muted-foreground">
                {users.length === 0
                  ? "No users are available for your access level."
                  : activeStatusFilter === "inactive"
                    ? "No inactive users found. Try adjusting your search or filter criteria."
                    : "Try adjusting your search or filter criteria."}
              </p>
            </Card>
          )}
        </div>
      </div>

      {/* Password Reset Modal */}
      {selectedUserForReset && (
        <PasswordResetModal
          isOpen={isPasswordResetModalOpen}
          onClose={handleClosePasswordResetModal}
          user={{
            id: selectedUserForReset.id,
            name: selectedUserForReset.name,
            email: selectedUserForReset.email,
            role: selectedUserForReset.role,
            department: selectedUserForReset.department,
          }}
        />
      )}

      {/* Edit User Modal */}
      {selectedUserForEdit && (
        <EditUserModal
          isOpen={isEditUserModalOpen}
          onClose={handleCloseEditUserModal}
          onUserUpdated={handleUserUpdated}
          user={{
            id: selectedUserForEdit.id,
            employeeId: selectedUserForEdit.employeeId,
            name: selectedUserForEdit.name,
            email: selectedUserForEdit.email,
            username: selectedUserForEdit.username,
            role: selectedUserForEdit.role,
            position: selectedUserForEdit.position,
            department: selectedUserForEdit.department,
            phone: selectedUserForEdit.phone,
            salary: selectedUserForEdit.salary,
            joinDate: selectedUserForEdit.joinDate,
            employmentType: selectedUserForEdit.employmentType,
            managerId: selectedUserForEdit.managerId,
            techStack: selectedUserForEdit.techStack,
            designSubTeam: selectedUserForEdit.designSubTeam,
          }}
        />
      )}

      {/* Remove User Confirmation Dialog */}
      <AlertDialog
        open={isRemoveUserDialogOpen}
        onOpenChange={setIsRemoveUserDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-red-600" />
              Mark User Inactive
            </AlertDialogTitle>
            <AlertDialogDescription>
              {selectedUserForRemoval && (
                <div className="space-y-3">
                  <p>
                    Are you sure you want to mark{" "}
                    <strong>{selectedUserForRemoval.name}</strong> as
                    inactive?
                  </p>

                  <div className="bg-muted/50 p-4 rounded-lg">
                    <div className="text-sm text-muted-foreground">
                      User details:
                    </div>
                    <div className="font-medium text-foreground">
                      {selectedUserForRemoval.name}
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {selectedUserForRemoval.email}
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {selectedUserForRemoval.role} •{" "}
                      {selectedUserForRemoval.department}
                    </div>
                  </div>

                  <div className="bg-red-50 p-4 rounded-lg border border-red-200">
                    <div className="flex items-start gap-2">
                      <AlertTriangle className="h-4 w-4 text-red-600 mt-0.5 flex-shrink-0" />
                      <div className="text-sm text-red-800">
                        <p className="font-medium">This action will:</p>
                        <ul className="mt-1 list-disc list-inside space-y-1">
                          <li>Deactivate the user&apos;s account</li>
                          <li>Prevent them from logging in</li>
                          <li>Preserve their data for historical records</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={handleCloseRemoveUserDialog}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmRemoveUser}
              className="bg-red-600 hover:bg-red-700"
              disabled={isRemovingUser}
            >
              {isRemovingUser ? (
                <>
                  <AppSpinner className="mr-2" />
                  Marking inactive...
                </>
              ) : (
                <>
                  <UserX className="h-4 w-4 mr-2" />
                  Mark Inactive
                </>
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Mark Active Confirmation Dialog */}
      <AlertDialog
        open={!!selectedUserForReactivation}
        onOpenChange={(open) => {
          if (!open) setSelectedUserForReactivation(null);
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <UserCheck className="h-5 w-5 text-green-600" />
              Mark User Active
            </AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div>
                {selectedUserForReactivation && (
                  <div className="space-y-3">
                    <p>
                      Are you sure you want to mark{" "}
                      <strong>{selectedUserForReactivation.name}</strong> as
                      active again?
                    </p>

                    <div className="bg-muted/50 p-4 rounded-lg">
                      <div className="text-sm text-muted-foreground">
                        User details:
                      </div>
                      <div className="font-medium text-foreground">
                        {selectedUserForReactivation.name}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        {selectedUserForReactivation.email}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {selectedUserForReactivation.role} •{" "}
                        {selectedUserForReactivation.department}
                      </div>
                    </div>

                    <div className="bg-green-50 p-4 rounded-lg border border-green-200">
                      <div className="text-sm text-green-800">
                        <p className="font-medium">This action will:</p>
                        <ul className="mt-1 list-disc list-inside space-y-1">
                          <li>Reactivate the user&apos;s account</li>
                          <li>Allow them to log in again</li>
                          <li>Show them in the active users list</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => setSelectedUserForReactivation(null)}
            >
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmReactivateUser}
              className="bg-green-600 hover:bg-green-700"
              disabled={isReactivatingUser}
            >
              {isReactivatingUser ? (
                <>
                  <AppSpinner className="mr-2" />
                  Marking active...
                </>
              ) : (
                <>
                  <UserCheck className="h-4 w-4 mr-2" />
                  Mark Active
                </>
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

/** SSO status: waiting for a role to be assigned, or access removed in SSO. */
function SsoBadge({ user, className = "" }: { user: { ssoPending?: boolean; ssoRevoked?: boolean }; className?: string }) {
  if (user.ssoRevoked) {
    return (
      <Badge variant="outline" className={`w-fit whitespace-nowrap border-destructive/40 px-2 py-0 text-[10px] text-destructive ${className}`} title="Access to Pulse was removed in SSO">
        SSO access removed
      </Badge>
    );
  }
  if (user.ssoPending) {
    return (
      <Badge variant="outline" className={`w-fit whitespace-nowrap border-amber-400 bg-amber-50 px-2 py-0 text-[10px] text-amber-700 ${className}`} title="Added from SSO. Edit the user and save a role to give access.">
        Needs role (SSO)
      </Badge>
    );
  }
  return null;
}
