'use client';

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import DataTable, { Column } from '@/components/ui/DataTable';
import Pagination from '@/components/ui/Pagination';
import FilterPanel from '@/components/ui/FilterPanel';
import Toolbar from '@/components/ui/Toolbar';
import Modal from '@/components/ui/CustomModal';
import CommonTimelineModal from '@/components/ui/CommonTimelineModal';
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2 } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────────

interface Employee {
  id: string;
  employee_id: string;
  first_name: string;
  last_name: string;
  work_email: string;
  work_phone: string | null;
  date_of_birth: string | null;
  gender: string | null;
  city: string | null;
  avatar_url: string | null;
  status: 'active' | 'inactive' | 'resigned' | 'terminated';
  role: string | null;
  deleted_at: string | null;
  created_at: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface Role {
  id: string;
  name: string;
  label: string;
}

interface Permission {
  id: string;
  name: string;
  module: string;
  action: string;
}

interface TabCounts {
  active: number;
  deleted: number;
}

interface EmployeesTableProps {
  canEdit: boolean;
  canDelete: boolean;
  canBulkDelete: boolean;
  canActivateDeactivate: boolean;
  canLogoutDevices: boolean;
  canChangePassword: boolean;
  canManageOverrides: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canBulkRestore: boolean;
  canViewTimeline: boolean;
  initialEmployees: {
    employees: Employee[];
    pagination: PaginationData;
  };
  initialCounts: TabCounts;
  roles: Role[];
  allPermissions: Permission[];
}

type TabType = 'active' | 'deleted';

interface ActiveFilters {
  search: string;
  status: string;
  startDate: string;
  endDate: string;
}

interface DeletedFilters {
  search: string;
  startDate: string;
  endDate: string;
}

interface ModalConfig {
  isOpen: boolean;
  type: 'danger' | 'warning' | 'info' | 'success';
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm: () => void;
}

interface TimelineModalState {
  isOpen: boolean;
  entityId: string;
  entityName: string;
}

type StatusType = 'active' | 'inactive' | 'resigned' | 'terminated';

// ─── Constants ────────────────────────────────────────────────────────────────

const STATUS_COLORS = {
  active: { bg: 'var(--color-success-light)', text: 'var(--color-success)' },
  inactive: { bg: 'var(--color-warning-light)', text: 'var(--color-warning)' },
  resigned: { bg: 'var(--color-info-light)', text: 'var(--color-info)' },
  terminated: { bg: 'var(--color-danger-light)', text: 'var(--color-danger)' },
} as const;

const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = { search: '', status: '', startDate: '', endDate: '' };
const EMPTY_DELETED_FILTERS: DeletedFilters = { search: '', startDate: '', endDate: '' };

const MODAL_CLOSED: ModalConfig = {
  isOpen: false, type: 'danger', title: '', message: '',
  confirmText: 'Confirm', cancelText: 'Cancel', onConfirm: () => {},
};

const TIMELINE_MODAL_CLOSED: TimelineModalState = { isOpen: false, entityId: '', entityName: '' };

// ─── API Helpers ──────────────────────────────────────────────────────────────

async function fetchEmployeesApi(
  page: number,
  tab: TabType,
  active: ActiveFilters,
  deleted: DeletedFilters,
  signal: AbortSignal,
) {
  const params = new URLSearchParams({
    page: String(page),
    limit: '10',
    includeDeleted: tab === 'deleted' ? 'true' : 'false',
  });

  if (tab === 'deleted') {
    if (deleted.search.trim()) params.append('search', deleted.search.trim());
    if (deleted.startDate) params.append('deletedStartDate', deleted.startDate);
    if (deleted.endDate) params.append('deletedEndDate', deleted.endDate);
  } else {
    if (active.search.trim()) params.append('search', active.search.trim());
    if (active.status) params.append('status', active.status);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/employees?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch employees');
  return res.json() as Promise<{ data: { employees: Employee[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/employees/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: StatusType }) {
  const colors = STATUS_COLORS[status] || STATUS_COLORS.active;
  return (
    <span
      className="inline-flex px-2 py-1 text-xs font-medium rounded-full capitalize"
      style={{ background: colors.bg, color: colors.text }}
    >
      {status}
    </span>
  );
}

function DeletedBadge() {
  return (
    <span
      className="inline-flex px-2 py-1 text-xs font-medium rounded-full"
      style={{ background: 'var(--color-danger-light)', color: 'var(--color-danger)' }}
    >
      Deleted
    </span>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function EmployeesTable({
  canEdit,
  canDelete,
  canBulkDelete,
  canActivateDeactivate,
  canLogoutDevices,
  canViewDeleted,
  canPermanentDelete,
  canRestore,
  canBulkRestore,
  canViewTimeline,
  initialEmployees,
  initialCounts,
}: EmployeesTableProps) {
  const router = useRouter();

  // ── Core state ────────────────────────────────────────────────────────────
  const [employees, setEmployees] = useState<Employee[]>(initialEmployees.employees);
  const [pagination, setPagination] = useState<PaginationData>(initialEmployees.pagination);
  const [counts, setCounts] = useState<TabCounts>(initialCounts);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('active');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [showFilters, setShowFilters] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);
  const [imageErrors, setImageErrors] = useState<Set<string>>(new Set());

  // ── Timeline state ──────────────────────────────────────────────────────
  const [timelineModal, setTimelineModal] = useState<TimelineModalState>(TIMELINE_MODAL_CLOSED);

  // ── Committed filters ─────────────────────────────────────────────────────
  const [activeFilters, setActiveFilters] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [deletedFilters, setDeletedFilters] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Draft filters ─────────────────────────────────────────────────────────
  const [draftActive, setDraftActive] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [draftDeleted, setDraftDeleted] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Refs ──────────────────────────────────────────────────────────────────
  const abortRef = useRef<AbortController | null>(null);
  const employeesRef = useRef(employees);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { employeesRef.current = employees; }, [employees]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  // ── Fetch employees ───────────────────────────────────────────────────────
  const fetchEmployees = useCallback(async (
    page: number,
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
  ) => {
    abortRef.current?.abort();
    const ctrl = new AbortController();
    abortRef.current = ctrl;

    setLoading(true);
    try {
      const json = await fetchEmployeesApi(page, tab, committed.active, committed.deleted, ctrl.signal);
      setEmployees(json.data.employees);
      setPagination(json.data.pagination);
      setCurrentPage(page);
      setSelectedIds(new Set());
    } catch (err) {
      if ((err as Error).name === 'AbortError') return;
      console.error('Failed to fetch employees:', err);
      toast.error('Failed to load employees');
    } finally {
      if (abortRef.current === ctrl) setLoading(false);
    }
  }, []);

  const refreshCounts = useCallback(async () => {
    try {
      const updated = await fetchCountsApi();
      setCounts(updated);
    } catch {
      console.warn('Could not refresh employee counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(async (
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
    page: number,
  ) => {
    await Promise.all([
      fetchEmployees(page, tab, committed),
      refreshCounts(),
    ]);
  }, [fetchEmployees, refreshCounts]);

  // ── Modal helpers ─────────────────────────────────────────────────────────
  const closeModal = useCallback(() => {
    if (!isDeleting) setModal(MODAL_CLOSED);
  }, [isDeleting]);

  const openModal = useCallback((config: Omit<ModalConfig, 'isOpen'>) => {
    setModal({ isOpen: true, ...config });
  }, []);

  // ── Timeline handlers ─────────────────────────────────────────────────────
  const handleTimelineClick = useCallback((employee: Employee) => {
    setTimelineModal({ isOpen: true, entityId: employee.id, entityName: `${employee.first_name} ${employee.last_name}` });
  }, []);

  const handleTimelineClose = useCallback(() => {
    setTimelineModal(TIMELINE_MODAL_CLOSED);
  }, []);

  // ── CRUD operations ───────────────────────────────────────────────────────

  const handleRestoreEmployee = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/employees/${id}/restore`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employee restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore employee');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkRestore = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/employees/bulk/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: [...selectedRef.current] }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employees restored successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to restore employees');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handlePermanentDelete = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/employees/${id}/permanent`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employee permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete employee');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkPermanentDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/employees/bulk/permanent', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: [...selectedRef.current] }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employees permanently deleted');
      } else {
        toast.error((await res.json()).message || 'Failed to delete employees');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleDeleteEmployee = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/employees/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employee deleted successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to delete employee');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  const handleBulkDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const res = await fetch('/api/employees/bulk', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: [...selectedRef.current] }),
      });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success('Employees deleted successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to delete employees');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── Status change handler ──────────────────────────────────────────────────

  const handleStatusChange = useCallback(async (id: string, newStatus: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/employees/${id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      });
      
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation(activeTab, { active: activeFilters, deleted: deletedFilters }, currentPage);
        toast.success(`Employee ${newStatus === 'active' ? 'activated' : 'deactivated'} successfully`);
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, `Failed to update status`));
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, [refreshAfterMutation, activeTab, activeFilters, deletedFilters, currentPage]);

  // ── Action handlers ───────────────────────────────────────────────────────

  const handleEditClick = useCallback((id: string) => {
    router.push(`/admin/dashboard/employees/edit/${id}`);
  }, [router]);

  const handleDeleteClick = useCallback((employee: Employee) => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Delete Employee',
        message: `Are you sure you want to permanently delete "${employee.first_name} ${employee.last_name}"? This cannot be undone.`,
        confirmText: 'Permanently Delete',
        cancelText: 'Cancel',
        onConfirm: () => handlePermanentDelete(employee.id),
      });
      return;
    }
    openModal({
      type: 'danger',
      title: 'Delete Employee',
      message: `Are you sure you want to delete "${employee.first_name} ${employee.last_name}"? It will move to deleted items.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDeleteEmployee(employee.id),
    });
  }, [activeTab, handleDeleteEmployee, handlePermanentDelete, openModal]);

  const handleRestoreClick = useCallback((employee: Employee) => {
    openModal({
      type: 'info',
      title: 'Restore Employee',
      message: `Restore "${employee.first_name} ${employee.last_name}"?`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestoreEmployee(employee.id),
    });
  }, [handleRestoreEmployee, openModal]);

  const handleActivateClick = useCallback((employee: Employee) => {
    openModal({
      type: 'success',
      title: 'Activate Employee',
      message: `Activate "${employee.first_name} ${employee.last_name}"?`,
      confirmText: 'Activate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(employee.id, 'active'),
    });
  }, [handleStatusChange, openModal]);

  const handleDeactivateClick = useCallback((employee: Employee) => {
    openModal({
      type: 'warning',
      title: 'Deactivate Employee',
      message: `Deactivate "${employee.first_name} ${employee.last_name}"?`,
      confirmText: 'Deactivate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(employee.id, 'inactive'),
    });
  }, [handleStatusChange, openModal]);

  const handleLogoutDevices = useCallback(async (id: string) => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/employees/${id}/logout`, { method: 'POST' });
      if (res.ok) {
        setModal(MODAL_CLOSED);
        toast.success('Logged out from all devices successfully');
      } else {
        toast.error((await res.json()).message || 'Failed to logout from devices');
      }
    } catch { toast.error('Network error — please try again'); }
    finally { setIsDeleting(false); }
  }, []);

  const handleLogoutClick = useCallback((employee: Employee) => {
    openModal({
      type: 'warning',
      title: 'Logout from All Devices',
      message: `Logout "${employee.first_name} ${employee.last_name}" from all devices?`,
      confirmText: 'Logout',
      cancelText: 'Cancel',
      onConfirm: () => handleLogoutDevices(employee.id),
    });
  }, [handleLogoutDevices, openModal]);

  // ── Bulk actions ──────────────────────────────────────────────────────────

  const showBulkDeleteConfirmation = useCallback(() => {

    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanent Bulk Delete',
        message: `Permanently delete ${selectedRef.current.size} employee(s)? This cannot be undone.`,
        confirmText: 'Permanently Delete All',
        cancelText: 'Cancel',
        onConfirm: handleBulkPermanentDelete,
      });
      return;
    }

    openModal({
      type: 'danger',
      title: 'Bulk Delete Employees',
      message: `Delete ${selectedRef.current.size} employee(s)? They will move to deleted items.`,
      confirmText: 'Delete All',
      cancelText: 'Cancel',
      onConfirm: handleBulkDelete,
    });
  }, [activeTab, handleBulkDelete, handleBulkPermanentDelete, openModal]);

  const showBulkRestoreConfirmation = useCallback(() => {
    openModal({
      type: 'info',
      title: 'Bulk Restore Employees',
      message: `Restore ${selectedRef.current.size} employee(s)?`,
      confirmText: 'Restore All',
      cancelText: 'Cancel',
      onConfirm: handleBulkRestore,
    });
  }, [handleBulkRestore, openModal]);

  // ── Tab change ────────────────────────────────────────────────────────────
  const handleTabChange = useCallback((tab: TabType) => {
    setActiveTab(tab);
    setShowFilters(false);
    const freshActive = EMPTY_ACTIVE_FILTERS;
    const freshDeleted = EMPTY_DELETED_FILTERS;
    setActiveFilters(freshActive);
    setDeletedFilters(freshDeleted);
    setDraftActive(freshActive);
    setDraftDeleted(freshDeleted);
    fetchEmployees(1, tab, { active: freshActive, deleted: freshDeleted });
  }, [fetchEmployees]);

  // ── Filter panel ──────────────────────────────────────────────────────────
  const handleToggleFilters = useCallback(() => {
    setShowFilters(prev => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchEmployees(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchEmployees(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchEmployees]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchEmployees(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchEmployees(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchEmployees]);

  // ── Pagination ────────────────────────────────────────────────────────────
  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchEmployees(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchEmployees, activeTab, activeFilters, deletedFilters]);

  // ── Selection ─────────────────────────────────────────────────────────────
  const handleSelectAll = useCallback(() => {
    setSelectedIds(prev =>
      prev.size === employeesRef.current.length
        ? new Set()
        : new Set(employeesRef.current.map(r => r.id)),
    );
  }, []);

  const handleSelectEmployee = useCallback((id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) { next.delete(id); } else { next.add(id); }
      return next;
    });
  }, []);

  // ── Image error handler ──────────────────────────────────────────────────
  const handleImageError = useCallback((employeeId: string) => {
    setImageErrors(prev => new Set(prev).add(employeeId));
  }, []);

  // ── Columns ───────────────────────────────────────────────────────────────
  const columns = useMemo<Column<Employee>[]>(() => {
    const cols: Column<Employee>[] = [
      {
        key: 'employee_id',
        header: 'Employee',
        render: (employee: Employee) => {
          const name = `${employee.first_name} ${employee.last_name}`;
          const hasAvatar = employee.avatar_url && !imageErrors.has(employee.id);
          
          return (
            <div className="flex items-center gap-3">
              {hasAvatar ? (
                <div className="relative w-8 h-8 rounded-full overflow-hidden shrink-0">
                  <Image
                    src={employee.avatar_url!}
                    alt={name}
                    fill
                    className="object-cover"
                    sizes="32px"
                    onError={() => handleImageError(employee.id)}
                  />
                </div>
              ) : (
                <div className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium shrink-0" style={{
                  background: 'var(--color-cta-light)',
                  color: 'var(--color-cta)'
                }}>
                  {employee.first_name[0]}{employee.last_name[0]}
                </div>
              )}
              <div>
                <div className="font-medium" style={{ color: 'var(--color-text)' }}>
                  {name}
                </div>
                <div className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                  {employee.employee_id}
                </div>
              </div>
            </div>
          );
        }
      },
      {
        key: 'work_email',
        header: 'Email',
        render: (employee) => (
          <div className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
            {employee.work_email}
          </div>
        )
      },
      {
        key: 'role',
        header: 'Role',
        render: (employee) => (
          <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
            {employee.role || 'Staff'}
          </span>
        )
      },
      {
        key: 'status',
        header: 'Status',
        render: (employee) => {
          if (employee.deleted_at) return <DeletedBadge />;
          return <StatusBadge status={employee.status as StatusType} />;
        }
      }
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (employee) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {employee.deleted_at ? new Date(employee.deleted_at).toLocaleDateString() : '-'}
          </span>
        )
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (employee) => {
        const actions: React.ReactNode[] = [];

        // Timeline button
        if (canViewTimeline) {
          actions.push(
            <button
              key="timeline"
              onClick={() => handleTimelineClick(employee)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-text-secondary)' }}
              title="View Timeline"
            >
              <History size={16} />
            </button>
          );
        }

        if (activeTab === 'deleted') {
          if (canRestore) actions.push(
            <button
              key="restore"
              onClick={() => handleRestoreClick(employee)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-success)' }}
              title="Restore Employee"
            >
              <ArchiveRestore size={16} />
            </button>
          );
          if (canPermanentDelete) actions.push(
            <button
              key="perm-del"
              onClick={() => handleDeleteClick(employee)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-danger)' }}
              title="Permanently Delete"
            >
              <Trash2 size={16} />
            </button>
          );
        } else {
          if (canEdit) actions.push(
            <button
              key="edit"
              onClick={() => handleEditClick(employee.id)}
              className="p-1 rounded hover:bg-surface-alt transition-colors"
              style={{ color: 'var(--color-info)' }}
              title="Edit Employee"
            >
              <SquarePen size={16} />
            </button>
          );

          if (canActivateDeactivate) {
            if (employee.status === 'active') {
              actions.push(
                <button
                  key="deactivate"
                  onClick={() => handleDeactivateClick(employee)}
                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                  style={{ color: 'var(--color-warning)' }}
                  title="Deactivate Employee"
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
                  </svg>
                </button>
              );
            } else if (employee.status !== 'terminated') {
              actions.push(
                <button
                  key="activate"
                  onClick={() => handleActivateClick(employee)}
                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                  style={{ color: 'var(--color-success)' }}
                  title="Activate Employee"
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M20 12.5A7.5 7.5 0 0 1 8 15m0 0L3 10m5 5L3 10"/>
                  </svg>
                </button>
              );
            }
          }

          if (canLogoutDevices) {
            actions.push(
              <button
                key="logout"
                onClick={() => handleLogoutClick(employee)}
                className="p-1 rounded hover:bg-surface-alt transition-colors"
                style={{ color: 'var(--color-danger)' }}
                title="Logout from all devices"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                  <polyline points="16 17 21 12 16 7"/>
                  <line x1="21" y1="12" x2="9" y2="12"/>
                </svg>
              </button>
            );
          }

          if (canDelete) {
            actions.push(
              <button
                key="delete"
                onClick={() => handleDeleteClick(employee)}
                className="p-1 rounded hover:bg-surface-alt transition-colors"
                style={{ color: 'var(--color-danger)' }}
                title="Delete Employee"
              >
                <Trash2 size={16} />
              </button>
            );
          }
        }

        return <div className="flex justify-end gap-2">{actions}</div>;
      }
    });

    return cols;
  }, [
    activeTab, canEdit, canDelete, canPermanentDelete, canRestore,
    canViewTimeline, canActivateDeactivate, canLogoutDevices,
    imageErrors, handleImageError,
    handleEditClick, handleDeleteClick, handleRestoreClick,
    handleTimelineClick, handleActivateClick, handleDeactivateClick,
    handleLogoutClick
  ]);

  // ── Filter fields ─────────────────────────────────────────────────────────
  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch',
          label: 'Search',
          type: 'text' as const,
          placeholder: 'Search by name, email, employee ID...',
          value: draftDeleted.search,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, search: v })),
        },
        {
          name: 'deletedStartDate',
          label: 'Deleted From',
          type: 'date' as const,
          value: draftDeleted.startDate,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, startDate: v })),
        },
        {
          name: 'deletedEndDate',
          label: 'Deleted To',
          type: 'date' as const,
          value: draftDeleted.endDate,
          onChange: (v: string) => setDraftDeleted(p => ({ ...p, endDate: v })),
        },
      ];
    }
    return [
      {
        name: 'search',
        label: 'Search',
        type: 'text' as const,
        placeholder: 'Search by name, email, employee ID...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive(p => ({ ...p, search: v })),
      },
      {
        name: 'status',
        label: 'Status',
        type: 'select' as const,
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'inactive', label: 'Inactive' },
          { value: 'resigned', label: 'Resigned' },
          { value: 'terminated', label: 'Terminated' },
        ],
        value: draftActive.status,
        onChange: (v: string) => setDraftActive(p => ({ ...p, status: v })),
      },
      {
        name: 'startDate',
        label: 'Created From',
        type: 'date' as const,
        value: draftActive.startDate,
        onChange: (v: string) => setDraftActive(p => ({ ...p, startDate: v })),
      },
      {
        name: 'endDate',
        label: 'Created To',
        type: 'date' as const,
        value: draftActive.endDate,
        onChange: (v: string) => setDraftActive(p => ({ ...p, endDate: v })),
      },
    ];
  }, [activeTab, draftActive, draftDeleted]);

  // ── Bulk action bar ───────────────────────────────────────────────────────
  const bulkActionBar = useMemo(() => {
    if (selectedIds.size === 0) return null;
    if (activeTab === 'deleted') {
      return (
        <div className="flex gap-2">
          {canBulkRestore && (
            <button
              onClick={showBulkRestoreConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-success)', color: 'white' }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 12a9 9 0 1 0 9-9m0 0v6m0-6h-6"/><path d="M21 12a9 9 0 1 1-9-9"/>
              </svg>
              Restore ({selectedIds.size})
            </button>
          )}
          {canPermanentDelete && (
            <button
              onClick={showBulkDeleteConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-danger)', color: 'white' }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
              </svg>
              Permanently Delete ({selectedIds.size})
            </button>
          )}
        </div>
      );
    }
    if (canBulkDelete) {
      return (
        <button
          onClick={showBulkDeleteConfirmation}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
          style={{ background: 'var(--color-danger)', color: 'white' }}
        >
          <svg width="16" height="16" {...ICON_STROKE}>
            <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
          </svg>
          Delete ({selectedIds.size})
        </button>
      );
    }
    return null;
  }, [
    selectedIds.size, activeTab,
    canBulkDelete, canBulkRestore, canPermanentDelete,
    showBulkDeleteConfirmation, showBulkRestoreConfirmation,
  ]);

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="space-y-4">
      {canViewDeleted && (
        <div className="flex border-b overflow-x-auto whitespace-nowrap" style={{ borderColor: 'var(--color-border)' }}>
          <button
            onClick={() => handleTabChange('active')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'active'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Active Employees ({counts.active})
          </button>
          <button
            onClick={() => handleTabChange('deleted')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'deleted'
                ? 'border-red-500 text-red-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Deleted Employees ({counts.deleted})
          </button>
        </div>
      )}

      <Toolbar
        leftActions={
          <>
            <button
              onClick={handleToggleFilters}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all border"
              style={{
                borderColor: 'var(--color-border)',
                color: 'var(--color-text)',
                background: 'var(--color-surface)'
              }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M6 12h12M10 18h4"/>
              </svg>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
            {bulkActionBar}
          </>
        }
      />

      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      <DataTable
        columns={columns}
        data={employees}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelectEmployee}
        onSelectAll={handleSelectAll}
        getRowId={(employee) => employee.id}
        showCheckbox={activeTab === 'deleted' ? (canPermanentDelete || canBulkRestore) : canBulkDelete}
        emptyMessage={activeTab === 'deleted' ? 'No deleted employees found' : 'No employees found'}
        skeletonRows={10}
      />

      {!loading && pagination.totalPages > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={pagination.totalPages}
          totalItems={pagination.total}
          itemsPerPage={pagination.limit}
          onPageChange={handlePageChange}
          showItemsInfo
        />
      )}

      {/* Confirmation Modal */}
      <Modal
        isOpen={modal.isOpen}
        onClose={closeModal}
        onConfirm={modal.onConfirm}
        title={modal.title}
        message={modal.message}
        confirmText={modal.confirmText}
        cancelText={modal.cancelText}
        type={modal.type}
        isLoading={isDeleting}
      />

      {/* Timeline Modal */}
      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={handleTimelineClose}
        entityType="employee"
        entityId={timelineModal.entityId}
        entityName={timelineModal.entityName}
      />
    </div>
  );
}