import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useWorkOrders, useWorkOrderMutations } from '../hooks/useWorkOrder';
import * as XLSX from 'xlsx';
import { 
  FaPlus, FaSearch, FaEdit, FaEye, FaTrash, FaCopy, FaEllipsisV, FaDownload, FaPrint, 
  FaFileExport, FaCheckCircle, FaClock, FaExclamationTriangle, FaTimes, FaFilter, 
  FaChevronDown, FaChevronUp, FaSave, FaStar, FaCheckSquare, FaSquare, FaFileExcel, FaFileCsv, FaLink 
} from 'react-icons/fa';
import LinkField from '../components/LinkField';
import { useUserPermissions } from '../hooks/useUserPermissions';
import useRoleProfile from '../hooks/useRoleProfile';
import { mergeWorkOrderFilters } from '../utils/roleAccess';
import workOrderService from '../services/workOrderService';
import ListPagination from '../components/ListPagination';
import ListFilterSortControls from '../components/ListFilterSortControls';
import { applyDateRangeToFilters } from '../utils/listFilterUtils';
import { buildMobileTeamSiteFilters } from '../utils/hospitalUtils';
import useUserPhccSiteFilter from '../hooks/useUserPhccSiteFilter';

// Export column configuration - will be defined inside component to use translations

type ExportFormat = 'csv' | 'excel';
type ExportScope = 'selected' | 'all_on_page' | 'all_with_filters';

interface ExportColumn {
  key: string;
  label: string;
  default: boolean;
}

interface ExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedCount: number;
  totalCount: number;
  pageCount: number;
  onExport: (scope: ExportScope, format: ExportFormat, columns: string[]) => void;
  isExporting: boolean;
  exportColumns: ExportColumn[];
}

const ExportModal: React.FC<ExportModalProps> = ({
  isOpen,
  onClose,
  selectedCount,
  totalCount,
  pageCount,
  onExport,
  isExporting,
  exportColumns
}) => {
  const { t } = useTranslation();
  const [scope, setScope] = useState<ExportScope>(selectedCount > 0 ? 'selected' : 'all_with_filters');
  const [format, setFormat] = useState<ExportFormat>('csv');
  const [selectedColumns, setSelectedColumns] = useState<string[]>(
    exportColumns.filter(c => c.default).map(c => c.key)
  );

  useEffect(() => {
    if (selectedCount > 0) {
      setScope('selected');
    } else {
      setScope('all_with_filters');
    }
  }, [selectedCount]);

  const toggleColumn = (key: string) => {
    setSelectedColumns(prev => 
      prev.includes(key) 
        ? prev.filter(k => k !== key)
        : [...prev, key]
    );
  };

  const selectAllColumns = () => {
    setSelectedColumns(exportColumns.map(c => c.key));
  };

  const selectDefaultColumns = () => {
    setSelectedColumns(exportColumns.filter(c => c.default).map(c => c.key));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[70] p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden animate-scale-in">
        {/* Header */}
        <div className="bg-gradient-to-r from-green-500 to-green-600 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FaFileExport className="text-white text-xl" />
              <h3 className="text-lg font-semibold text-white">{t('listPages.export')} {t('workOrders.title')}</h3>
            </div>
            <button
              onClick={onClose}
              className="text-white/80 hover:text-white transition-colors"
              disabled={isExporting}
            >
              <FaTimes size={20} />
            </button>
          </div>
        </div>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
          {/* Export Scope */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              What to Export
            </h4>
            <div className="space-y-2">
              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'selected' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              } ${selectedCount === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}>
                <input
                  type="radio"
                  name="scope"
                  value="selected"
                  checked={scope === 'selected'}
                  onChange={() => setScope('selected')}
                  disabled={selectedCount === 0}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    Selected Rows
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export {selectedCount} selected work order{selectedCount !== 1 ? 's' : ''}
                  </div>
                </div>
                {selectedCount > 0 && (
                  <span className="bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300 px-2 py-1 rounded text-xs font-medium">
                    {selectedCount} selected
                  </span>
                )}
              </label>

              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'all_on_page' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="scope"
                  value="all_on_page"
                  checked={scope === 'all_on_page'}
                  onChange={() => setScope('all_on_page')}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    Current Page
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export {pageCount} work order{pageCount !== 1 ? 's' : ''} on current page
                  </div>
                </div>
                <span className="bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 px-2 py-1 rounded text-xs font-medium">
                  {pageCount} rows
                </span>
              </label>

              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'all_with_filters' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="scope"
                  value="all_with_filters"
                  checked={scope === 'all_with_filters'}
                  onChange={() => setScope('all_with_filters')}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    All Records (with current filters)
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export all {totalCount} work order{totalCount !== 1 ? 's' : ''} matching current filters
                  </div>
                </div>
                <span className="bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300 px-2 py-1 rounded text-xs font-medium">
                  {totalCount} total
                </span>
              </label>
            </div>
          </div>

          {/* Export Format */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              Export Format
            </h4>
            <div className="flex gap-3">
              <label className={`flex-1 flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                format === 'csv' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="format"
                  value="csv"
                  checked={format === 'csv'}
                  onChange={() => setFormat('csv')}
                  className="text-green-600 focus:ring-green-500"
                />
                <FaFileCsv className="text-green-600 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">CSV</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">Comma-separated values</div>
                </div>
              </label>

              <label className={`flex-1 flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                format === 'excel' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="format"
                  value="excel"
                  checked={format === 'excel'}
                  onChange={() => setFormat('excel')}
                  className="text-green-600 focus:ring-green-500"
                />
                <FaFileExcel className="text-green-700 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">Excel</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">XLSX spreadsheet</div>
                </div>
              </label>
            </div>
          </div>

          {/* Column Selection */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                Columns to Export
              </h4>
              <div className="flex gap-2">
                <button
                  onClick={selectAllColumns}
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                >
                  Select All
                </button>
                <span className="text-gray-300 dark:text-gray-600">|</span>
                <button
                  onClick={selectDefaultColumns}
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                >
                  Reset to Default
                </button>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-48 overflow-y-auto p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
              {exportColumns.map(col => (
                <label
                  key={col.key}
                  className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-all ${
                    selectedColumns.includes(col.key)
                      ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300'
                      : 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-400'
                  }`}
                >
                  <input
                    type="checkbox"
                    checked={selectedColumns.includes(col.key)}
                    onChange={() => toggleColumn(col.key)}
                    className="rounded text-green-600 focus:ring-green-500"
                  />
                  <span className="text-sm truncate">{col.label}</span>
                </label>
              ))}
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
              {selectedColumns.length} column{selectedColumns.length !== 1 ? 's' : ''} selected
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <div className="text-sm text-gray-600 dark:text-gray-400">
            {scope === 'selected' && `Exporting ${selectedCount} selected row${selectedCount !== 1 ? 's' : ''}`}
            {scope === 'all_on_page' && `Exporting ${pageCount} row${pageCount !== 1 ? 's' : ''} from current page`}
            {scope === 'all_with_filters' && `Exporting all ${totalCount} row${totalCount !== 1 ? 's' : ''}`}
          </div>
          <div className="flex gap-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              disabled={isExporting}
            >
              Cancel
            </button>
            <button
              onClick={() => onExport(scope, format, selectedColumns)}
              disabled={selectedColumns.length === 0 || isExporting}
              className="px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isExporting ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  Exporting...
                </>
              ) : (
                <>
                  <FaDownload />
                  Export
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};


const WorkOrderList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();

  const page = useMemo(() => {
    const p = parseInt(searchParams.get('page') || '1', 10);
    return Math.max(0, Number.isNaN(p) ? 0 : p - 1);
  }, [searchParams]);

  const setPage = useCallback((zeroBasedPage: number) => {
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      next.set('page', String(zeroBasedPage + 1));
      return next;
    });
  }, [setSearchParams]);

  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const limit = 20;
  
  // Export column configuration with translations
  const EXPORT_COLUMNS = [
    { key: 'name', label: t('commonFields.workOrderId'), default: true },
    { key: 'asset', label: t('commonFields.assetId'), default: true },
    { key: 'asset_name', label: t('commonFields.assetName'), default: true },
    { key: 'work_order_type', label: t('commonFields.workOrderType'), default: true },
    { key: 'company', label: t('commonFields.company'), default: true },
    { key: 'site_name', label: t('commonFields.siteName') || 'Site Name', default: true },
    { key: 'department', label: t('commonFields.department'), default: true },
    { key: 'repair_status', label: t('commonFields.status'), default: true },
    { key: 'custom_priority_', label: t('commonFields.priority'), default: true },
    { key: 'custom_serial_number', label: t('commonFields.serialNumber'), default: false },
    { key: 'custom_manufacturer', label: t('commonFields.manufacturer'), default: false },
    { key: 'supplier', label: t('commonFields.supplier'), default: false },
    { key: 'description', label: t('commonFields.description'), default: false },
    { key: 'assigned_to', label: t('commonFields.assignedTo'), default: false },
    { key: 'scheduled_date', label: t('commonFields.scheduledDate'), default: false },
    { key: 'completed_date', label: t('commonFields.completedDate'), default: false },
    { key: 'creation', label: t('commonFields.createdOn'), default: true },
    { key: 'modified', label: t('commonFields.modifiedOn'), default: false },
    { key: 'owner', label: t('commonFields.createdBy'), default: false },
  ];

  // ✅ Check if filtered from Asset
  const assetFromUrl = searchParams.get('asset');
  const isFilteredFromAsset = !!assetFromUrl;

  // Track initial load
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  // Row selection state
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());

  // Export modal state
  const [showExportModal, setShowExportModal] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  // Get user permissions
  const { 
    permissionFilters, 
    loading: permissionsLoading, 
    error: permissionsError,
    hasAnyRestrictions
  } = useUserPermissions('Work_Order');
  const { roleProfile, userEmail } = useRoleProfile();

  const sortOptions = ['creation desc', 'creation asc', 'modified desc', 'modified asc', 'name asc', 'name desc'] as const;

  // Filter states (init from URL — persists when navigating back from detail)
  const [dateFilterBy, setDateFilterBy] = useState<'' | 'creation' | 'modified'>(() => (searchParams.get('date_filter_by') as '' | 'creation' | 'modified') || '');
  const [dateStart, setDateStart] = useState(() => searchParams.get('date_start') || '');
  const [dateEnd, setDateEnd] = useState(() => searchParams.get('date_end') || '');
  const [sortBy, setSortBy] = useState<string>(() => searchParams.get('sort_by') || 'modified desc');
  const [filterWorkOrderId, setFilterWorkOrderId] = useState(() => searchParams.get('work_order_id') || '');
  const [filterAsset, setFilterAsset] = useState(() => searchParams.get('asset') || '');
  const [filterType, setFilterType] = useState(() => searchParams.get('work_order_type') || '');
  const [filterCompany, setFilterCompany] = useState(() => searchParams.get('company') || '');
  const { userPhccSiteName, siteLocked } = useUserPhccSiteFilter();
  const [filterSiteName, setFilterSiteName] = useState(() => searchParams.get('site_name') || '');
  const [filterStatus, setFilterStatus] = useState(() => searchParams.get('status') || '');
  const [filterSerialNumber, setFilterSerialNumber] = useState(() => searchParams.get('serial_number') || '');
  const [filterManufacturer, setFilterManufacturer] = useState(() => searchParams.get('manufacturer') || '');
  const [filterSupplier, setFilterSupplier] = useState(() => searchParams.get('supplier') || '');
  const [filterDepartment, setFilterDepartment] = useState(() => searchParams.get('department') || '');
  const [filterPriority, setFilterPriority] = useState(() => searchParams.get('priority') || '');

  const filtersChangedOnce = useRef(false);
  const hasDateFilter = dateFilterBy && (dateStart || dateEnd);

  // Advanced filter UI states
  const [isFilterExpanded, setIsFilterExpanded] = useState(false);
  const [activeFilterCount, setActiveFilterCount] = useState(0);
  const [savedFilters, setSavedFilters] = useState<any[]>([]);
  const [showSaveFilterModal, setShowSaveFilterModal] = useState(false);
  const [filterPresetName, setFilterPresetName] = useState('');

  // Temporary states for text inputs
  const [tempSerialNumber, setTempSerialNumber] = useState(() => searchParams.get('serial_number') || '');

  // Debounce timer refs
  const serialNumberDebounceRef = useRef<number | null>(null);

  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(filterCompany, userPhccSiteName),
    [filterCompany, userPhccSiteName]
  );

  // Auto-apply user's PHCC site when set on profile
  useEffect(() => {
    if (siteLocked && userPhccSiteName) {
      setFilterSiteName(userPhccSiteName);
    }
  }, [siteLocked, userPhccSiteName]);

  // Load saved filters from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem('workOrderFilterPresets');
    if (saved) {
      setSavedFilters(JSON.parse(saved));
    }
  }, []);

  // Update active filter count
  useEffect(() => {
    const count = [
      filterWorkOrderId,
      filterAsset,
      filterType,
      filterCompany,
      filterSiteName,
      filterStatus,
      filterSerialNumber,
      filterManufacturer,
      filterSupplier,
      filterDepartment,
      filterPriority
    ].filter(Boolean).length + (hasDateFilter ? 1 : 0);
    setActiveFilterCount(count);
  }, [
    hasDateFilter,
    filterWorkOrderId,
    filterAsset,
    filterType,
    filterCompany,
    filterSiteName,
    filterStatus,
    filterSerialNumber,
    filterManufacturer,
    filterSupplier,
    filterDepartment,
    filterPriority
  ]);

  // Build filters object for API (reference pattern)
  const filters: Record<string, any> = {};
  if (filterWorkOrderId) filters.name = filterWorkOrderId;
  if (filterAsset) filters.asset = filterAsset;
  if (filterType) filters.work_order_type = filterType;
  if (filterCompany) filters.company = filterCompany;
  if (filterSiteName) filters.site_name = filterSiteName;
  if (filterStatus) {
    const statuses = filterStatus.split(',').map((s) => s.trim()).filter(Boolean);
    filters.repair_status = statuses.length > 1 ? ['in', statuses] : filterStatus;
  }
  if (filterSerialNumber) filters.custom_serial_number = ['like', `%${filterSerialNumber}%`];
  if (filterManufacturer) filters.custom_manufacturer = filterManufacturer;
  if (filterSupplier) filters.supplier = filterSupplier;
  if (filterDepartment) filters.department = filterDepartment;
  if (filterPriority) filters.custom_priority_ = filterPriority;
  Object.assign(filters, applyDateRangeToFilters({}, dateFilterBy, dateStart, dateEnd));

  const orderBy = sortOptions.includes(sortBy as (typeof sortOptions)[number]) ? sortBy : 'modified desc';

  const effectiveFilters = useMemo(
    () => mergeWorkOrderFilters(filters, permissionFilters, roleProfile, userEmail),
    [filters, permissionFilters, roleProfile, userEmail]
  );

  const { workOrders, totalCount, hasMore, loading, error, refetch } = useWorkOrders(
    effectiveFilters,
    limit,
    page * limit,
    orderBy,
    {}
  );

  const { deleteWorkOrder, loading: mutationLoading } = useWorkOrderMutations();

  // Mark initial load complete
  useEffect(() => {
    if (!loading && !initialLoadComplete && !permissionsLoading) {
      setInitialLoadComplete(true);
    }
  }, [loading, initialLoadComplete, permissionsLoading]);

  // Sync filters to URL when user changes a filter (skip first mount)
  useEffect(() => {
    if (!filtersChangedOnce.current) {
      filtersChangedOnce.current = true;
      return;
    }
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      if (dateFilterBy) next.set('date_filter_by', dateFilterBy); else next.delete('date_filter_by');
      if (dateStart) next.set('date_start', dateStart); else next.delete('date_start');
      if (dateEnd) next.set('date_end', dateEnd); else next.delete('date_end');
      if (filterWorkOrderId) next.set('work_order_id', filterWorkOrderId); else next.delete('work_order_id');
      if (filterAsset) next.set('asset', filterAsset); else next.delete('asset');
      if (filterType) next.set('work_order_type', filterType); else next.delete('work_order_type');
      if (filterCompany) next.set('company', filterCompany); else next.delete('company');
      if (filterSiteName) next.set('site_name', filterSiteName); else next.delete('site_name');
      if (filterStatus) next.set('status', filterStatus); else next.delete('status');
      if (filterSerialNumber) next.set('serial_number', filterSerialNumber); else next.delete('serial_number');
      if (filterManufacturer) next.set('manufacturer', filterManufacturer); else next.delete('manufacturer');
      if (filterSupplier) next.set('supplier', filterSupplier); else next.delete('supplier');
      if (filterDepartment) next.set('department', filterDepartment); else next.delete('department');
      if (filterPriority) next.set('priority', filterPriority); else next.delete('priority');
      if (sortBy && sortBy !== 'modified desc') next.set('sort_by', sortBy); else next.delete('sort_by');
      next.set('page', '1');
      return next;
    });
  }, [
    dateFilterBy, dateStart, dateEnd, filterWorkOrderId, filterAsset, filterType,
    filterCompany, filterSiteName, filterStatus, filterSerialNumber, filterManufacturer,
    filterSupplier, filterDepartment, filterPriority, sortBy,
  ]);

  // Clear selection on filter/page change
  useEffect(() => {
    setSelectedRows(new Set());
  }, [
    dateFilterBy, dateStart, dateEnd, filterWorkOrderId, filterAsset, filterType,
    filterCompany, filterSiteName, filterStatus, filterSerialNumber, filterManufacturer,
    filterSupplier, filterDepartment, filterPriority, page,
  ]);

  // Debounce function for serial number
  const handleSerialNumberChange = (value: string) => {
    setTempSerialNumber(value);
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
    serialNumberDebounceRef.current = window.setTimeout(() => {
      setFilterSerialNumber(value);
    }, 800);
  };

  // Handle Enter key press
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
      setFilterSerialNumber(tempSerialNumber);
    }
  };

  // Save filter preset
  const handleSaveFilterPreset = () => {
    if (!filterPresetName.trim()) {
      alert('Please enter a filter name');
      return;
    }
    
    const preset = {
      id: Date.now(),
      name: filterPresetName,
      filters: {
        dateFilterBy,
        dateStart,
        dateEnd,
        sortBy,
        filterWorkOrderId,
        filterAsset,
        filterType,
        filterCompany,
        filterSiteName,
        filterStatus,
        filterSerialNumber,
        filterManufacturer,
        filterSupplier,
        filterDepartment,
        filterPriority
      }
    };
    
    const updated = [...savedFilters, preset];
    setSavedFilters(updated);
    setFilterPresetName('');
    setShowSaveFilterModal(false);
    localStorage.setItem('workOrderFilterPresets', JSON.stringify(updated));
  };

  // Load filter preset
  const handleLoadFilterPreset = (preset: any) => {
    const f = preset.filters;
    setDateFilterBy(f.dateFilterBy || '');
    setDateStart(f.dateStart || '');
    setDateEnd(f.dateEnd || '');
    setSortBy(f.sortBy || 'modified desc');
    setFilterWorkOrderId(f.filterWorkOrderId || '');
    setFilterAsset(f.filterAsset || '');
    setFilterType(f.filterType || '');
    setFilterCompany(f.filterCompany || '');
    setFilterSiteName(f.filterSiteName || '');
    setFilterStatus(f.filterStatus || '');
    setFilterSerialNumber(f.filterSerialNumber || '');
    setTempSerialNumber(f.filterSerialNumber || '');
    setFilterManufacturer(f.filterManufacturer || '');
    setFilterSupplier(f.filterSupplier || '');
    setFilterDepartment(f.filterDepartment || '');
    setFilterPriority(f.filterPriority || '');
  };

  // Delete filter preset
  const handleDeleteFilterPreset = (id: number) => {
    const updated = savedFilters.filter(f => f.id !== id);
    setSavedFilters(updated);
    localStorage.setItem('workOrderFilterPresets', JSON.stringify(updated));
  };

  // Cleanup timeouts on unmount
  useEffect(() => {
    return () => {
      if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
    };
  }, []);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setActionMenuOpen(null);
      }
    };

    if (actionMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [actionMenuOpen]);

  // Row selection handlers
  const handleSelectRow = (workOrderName: string) => {
    setSelectedRows(prev => {
      const newSet = new Set(prev);
      if (newSet.has(workOrderName)) {
        newSet.delete(workOrderName);
      } else {
        newSet.add(workOrderName);
      }
      return newSet;
    });
  };

  const handleSelectAll = () => {
    if (selectedRows.size === workOrders.length) {
      setSelectedRows(new Set());
    } else {
      setSelectedRows(new Set(workOrders.map(wo => wo.name)));
    }
  };

  const isAllSelected = workOrders.length > 0 && selectedRows.size === workOrders.length;
  const isSomeSelected = selectedRows.size > 0 && selectedRows.size < workOrders.length;

  // Fetch all work orders for export
  const fetchAllWorkOrdersForExport = useCallback(async (): Promise<any[]> => {
    const allWorkOrders: any[] = [];
    let currentPage = 0;
    const pageSize = 100;
    let hasMoreData = true;

    while (hasMoreData) {
      try {
        const response = await workOrderService.getWorkOrders(
          effectiveFilters,
          ['*'],
          pageSize,
          currentPage * pageSize,
          orderBy
        );
        const results = response.work_orders || [];

        allWorkOrders.push(...results);

        if (results.length < pageSize) {
          hasMoreData = false;
        } else {
          currentPage++;
        }

        if (currentPage > 100) {
          console.warn('Export safety limit reached');
          hasMoreData = false;
        }
      } catch (error) {
        console.error('Error fetching work orders for export:', error);
        throw error;
      }
    }

    return allWorkOrders;
  }, [effectiveFilters, orderBy]);

  // Export handler
  const handleExport = async (scope: ExportScope, format: ExportFormat, columns: string[]) => {
    setIsExporting(true);

    try {
      let dataToExport: any[] = [];

      switch (scope) {
        case 'selected':
          dataToExport = workOrders.filter(wo => selectedRows.has(wo.name));
          break;
        case 'all_on_page':
          dataToExport = workOrders;
          break;
        case 'all_with_filters':
          dataToExport = await fetchAllWorkOrdersForExport();
          break;
      }

      if (dataToExport.length === 0) {
        alert('No data to export');
        return;
      }

      const columnLabels = columns.map(key => {
        const col = EXPORT_COLUMNS.find(c => c.key === key);
        return col?.label || key;
      });

      if (format === 'csv') {
        const csvContent = [
          columnLabels.join(','),
          ...dataToExport.map(wo => 
            columns.map(key => {
              let value = wo[key] || '';
              if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
                value = `"${value.replace(/"/g, '""')}"`;
              }
              return value;
            }).join(',')
          )
        ].join('\n');

        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `work_orders_export_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
        URL.revokeObjectURL(url);

      } else if (format === 'excel') {
        const worksheetData = [
          columnLabels,
          ...dataToExport.map(wo =>
            columns.map(key => wo[key] || '')
          )
        ];

        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Work Orders');

        XLSX.writeFile(workbook, `work_orders_export_${new Date().toISOString().split('T')[0]}.xlsx`);
      }

      setShowExportModal(false);
      setSelectedRows(new Set());
      
    } catch (error) {
      console.error('Export failed:', error);
      alert(`Export failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsExporting(false);
    }
  };

  const handleCreateNew = () => navigate('/work-orders/new');
  const handleView = (workOrderName: string) => navigate(`/work-orders/${workOrderName}`);
  const handleEdit = (workOrderName: string) => navigate(`/work-orders/${workOrderName}`);
  const handleDuplicate = (workOrderName: string) => navigate(`/work-orders/new?duplicate=${workOrderName}`);

  const handleDelete = async (workOrderName: string) => {
    try {
      await deleteWorkOrder(workOrderName);
      setDeleteConfirmOpen(null);
      refetch();
      alert('Work order deleted successfully!');
    } catch (err) {
      alert(`Failed to delete work order: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleExportSingle = (workOrder: any) => {
    const dataStr = JSON.stringify(workOrder, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `work_order_${workOrder.name}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const handlePrint = (workOrderName: string) => {
    window.open(`/work-orders/${workOrderName}?print=true`, '_blank');
  };

  const handleClearFilters = () => {
    setDateFilterBy('');
    setDateStart('');
    setDateEnd('');
    setSortBy('modified desc');
    setFilterWorkOrderId('');
    setFilterAsset('');
    setFilterType('');
    setFilterCompany('');
    if (!siteLocked) {
      setFilterSiteName('');
    }
    setFilterStatus('');
    setFilterSerialNumber('');
    setTempSerialNumber('');
    setFilterManufacturer('');
    setFilterSupplier('');
    setFilterDepartment('');
    setFilterPriority('');

    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      next.delete('date_filter_by');
      next.delete('date_start');
      next.delete('date_end');
      next.delete('sort_by');
      next.delete('work_order_id');
      next.delete('asset');
      next.delete('work_order_type');
      next.delete('company');
      next.delete('site_name');
      next.delete('status');
      next.delete('serial_number');
      next.delete('manufacturer');
      next.delete('supplier');
      next.delete('department');
      next.delete('priority');
      next.set('page', '1');
      return next;
    });

    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
  };

  const hasActiveFilters = hasDateFilter || filterWorkOrderId || filterAsset || filterType || filterCompany ||
                          filterSiteName || filterStatus || filterSerialNumber || filterManufacturer ||
                          filterSupplier || filterDepartment || filterPriority;

  const formatDate = (dateString?: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getStatusIcon = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'completed':
        return <FaCheckCircle className="text-green-500" />;
      case 'in progress':
        return <FaClock className="text-blue-500" />;
      case 'pending':
        return <FaExclamationTriangle className="text-yellow-500" />;
      default:
        return <FaClock className="text-gray-400" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'completed':
        return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';
      case 'in progress':
        return 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300';
      case 'pending':
      case 'open':
        return 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300';
      case 'cancelled':
        return 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300';
      default:
        return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority?.toLowerCase()) {
      case 'high':
      case 'urgent':
        return 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300';
      case 'medium':
        return 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300';
      case 'low':
        return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';
      default:
        return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300';
    }
  };

  // Loading state for permissions
  if (permissionsLoading && !initialLoadComplete) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading permissions...</p>
        </div>
      </div>
    );
  }

  // Error state for permissions
  if (permissionsError) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">⚠️ Permission Error</h2>
          <div className="text-red-700 dark:text-red-400 space-y-3">
            <p><strong>Unable to load user permissions.</strong></p>
            <p>{permissionsError}</p>
            <button 
              onClick={() => window.location.reload()}
              className="mt-2 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded"
            >
              Retry
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Full-page loader on initial load
  if (loading && !initialLoadComplete) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading work orders...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-yellow-800 dark:text-yellow-300 mb-4">⚠️ Work Order API Not Available</h2>
          <div className="text-yellow-700 dark:text-yellow-400 space-y-3">
            <p><strong>The Work Order API endpoint is not deployed yet.</strong></p>
            <button 
              onClick={() => navigate('/work-orders/new')}
              className="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded"
            >
              Try Creating a New Work Order (Demo)
            </button>
            <button 
              onClick={refetch}
              className="mt-2 ml-2 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded"
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between lg:items-center">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 dark:text-white break-words">{t('workOrders.title')}</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Total: {totalCount} work order{totalCount !== 1 ? 's' : ''}
            {selectedRows.size > 0 && (
              <span className="ml-2 text-blue-600 dark:text-blue-400">
                • {selectedRows.size} selected
              </span>
            )}
            {loading && initialLoadComplete && (
              <span className="ml-2 inline-flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400">
                <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500"></div>
                Updating...
              </span>
            )}
          </p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => setShowExportModal(true)}
            className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all"
            disabled={totalCount === 0}
          >
            <FaFileExport />
            <span className="font-medium">{t('listPages.export')}</span>
            {selectedRows.size > 0 && (
              <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">
                {selectedRows.size}
              </span>
            )}
          </button>
          <button
            onClick={handleCreateNew}
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow-lg transition-all hover:shadow-xl"
          >
            <FaPlus />
            <span className="font-medium">{t('workOrders.addWorkOrder')}</span>
          </button>
        </div>
      </div>

      {/* Advanced Filter Panel */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 mb-4">
        {/* Filter Header */}
        <div className="bg-gradient-to-r from-blue-500 to-blue-600 dark:from-blue-600 dark:to-blue-700 px-4 py-3 rounded-t-lg">
          <div className="flex items-center justify-between gap-4">
            {/* Left Side - Toggle & Title */}
            <div className="flex items-center gap-3 flex-shrink-0">
              <button
                onClick={() => setIsFilterExpanded(!isFilterExpanded)}
                className="text-white hover:bg-white/20 p-2 rounded-lg transition-all"
              >
                {isFilterExpanded ? <FaChevronUp size={14} /> : <FaChevronDown size={14} />}
              </button>
              
              <div className="flex items-center gap-2">
                <FaFilter className="text-white" size={16} />
                <h3 className="text-white font-semibold text-sm">Filters</h3>
              </div>
              
              {activeFilterCount > 0 && (
                <span className="bg-white text-blue-600 px-2 py-0.5 rounded-full text-xs font-bold">
                  {activeFilterCount}
                </span>
              )}
            </div>

            {/* Center - Active Filter Tags */}
            {hasActiveFilters && (
              <div className="flex-1 overflow-x-auto scrollbar-hide mx-2">
                <div className="flex items-center gap-2 py-1">
                  {hasDateFilter && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-indigo-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">{t('filters.filterBy')}:</span> {dateFilterBy === 'creation' ? t('filters.createdDate') : t('filters.latestModifiedDate')} {dateStart && ` ${dateStart}`} {dateEnd && ` - ${dateEnd}`}
                      <button onClick={(e) => { e.stopPropagation(); setDateFilterBy(''); setDateStart(''); setDateEnd(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterWorkOrderId && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-blue-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">WO ID:</span> {filterWorkOrderId}
                      <button onClick={(e) => { e.stopPropagation(); setFilterWorkOrderId(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterAsset && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-cyan-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Asset:</span> {filterAsset}
                      {/* <button onClick={(e) => { e.stopPropagation(); setFilterAsset(''); }} className="hover:text-red-500 transition-colors"> */}
                      <button onClick={(e) => { e.stopPropagation(); setFilterAsset(''); searchParams.delete('asset'); setSearchParams(searchParams); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterType && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-purple-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Type:</span> {filterType}
                      <button onClick={(e) => { e.stopPropagation(); setFilterType(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterCompany && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-green-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Hospital:</span> {filterCompany}
                      <button onClick={(e) => { e.stopPropagation(); setFilterCompany(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSiteName && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-emerald-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Site:</span> {filterSiteName}
                      {!siteLocked && (
                        <button onClick={(e) => { e.stopPropagation(); setFilterSiteName(''); searchParams.delete('site_name'); setSearchParams(searchParams); }} className="hover:text-red-500 transition-colors">
                          <FaTimes className="text-[9px]" />
                        </button>
                      )}
                    </span>
                  )}
                  {filterStatus && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-orange-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Status:</span> {filterStatus}
                      <button onClick={(e) => { e.stopPropagation(); setFilterStatus(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSerialNumber && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-lime-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Serial:</span> {filterSerialNumber}
                      <button onClick={(e) => { e.stopPropagation(); setFilterSerialNumber(''); setTempSerialNumber(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterManufacturer && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-indigo-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Mfr:</span> {filterManufacturer}
                      <button onClick={(e) => { e.stopPropagation(); setFilterManufacturer(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSupplier && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-teal-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Supplier:</span> {filterSupplier}
                      <button onClick={(e) => { e.stopPropagation(); setFilterSupplier(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterDepartment && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-yellow-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Dept:</span> {filterDepartment}
                      <button onClick={(e) => { e.stopPropagation(); setFilterDepartment(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterPriority && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-red-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Priority:</span> {filterPriority}
                      <button onClick={(e) => { e.stopPropagation(); setFilterPriority(''); }} className="hover:text-red-500 transition-colors">
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                </div>
              </div>
            )}

            {/* Right Side - Action Buttons */}
            <div className="flex items-center gap-2 flex-shrink-0">
              {activeFilterCount > 0 && (
                <button
                  onClick={() => setShowSaveFilterModal(true)}
                  className="px-3 py-1.5 bg-white text-blue-600 hover:bg-blue-50 rounded-md text-xs font-medium transition-all flex items-center gap-1.5"
                >
                  <FaSave size={12} />
                  <span className="hidden sm:inline">Save</span>
                </button>
              )}
              {hasActiveFilters && (
                <button
                  onClick={handleClearFilters}
                  className="px-3 py-1.5 bg-red-500 hover:bg-red-600 text-white rounded-md text-xs font-medium transition-all flex items-center gap-1.5"
                >
                  <FaTimes size={12} />
                  <span className="hidden sm:inline">Clear</span>
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Expandable Filter Content */}
        {isFilterExpanded && (
          <div className="p-4">
            {/* Saved Filter Presets */}
            {savedFilters.length > 0 && (
              <div className="mb-4 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
                  <FaStar className="text-yellow-500" size={12} />
                  Saved Filters
                </h4>
                <div className="flex flex-wrap gap-2">
                  {savedFilters.map((preset) => (
                    <div
                      key={preset.id}
                      className="group relative inline-flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-100 to-blue-100 dark:from-purple-900/30 dark:to-blue-900/30 border border-purple-200 dark:border-purple-700 rounded-lg hover:shadow-md transition-all"
                    >
                      <button
                        onClick={() => handleLoadFilterPreset(preset)}
                        className="text-xs font-medium text-purple-700 dark:text-purple-300"
                      >
                        {preset.name}
                      </button>
                      <button
                        onClick={() => handleDeleteFilterPreset(preset.id)}
                        className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 transition-opacity"
                      >
                        <FaTrash size={10} />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Filter Grid */}
            <div className="space-y-5">
              <div className="bg-gray-50 dark:bg-gray-900/50 p-3 rounded-lg">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3">
                  <ListFilterSortControls
                    sortBy={sortBy}
                    dateFilterBy={dateFilterBy}
                    dateStart={dateStart}
                    dateEnd={dateEnd}
                    onSortByChange={setSortBy}
                    onDateFilterByChange={setDateFilterBy}
                    onDateStartChange={setDateStart}
                    onDateEndChange={setDateEnd}
                  />
                  {/* Work Order ID */}
                  <div className="relative z-[60]">
                    <LinkField
                      label="Work Order ID"
                      doctype="Work_Order"
                      value={filterWorkOrderId}
                      onChange={(val) => setFilterWorkOrderId(val)}
                      placeholder="Select WO ID"
                      disabled={false}
                      compact={true}
                    />
                    {filterWorkOrderId && (
                      <button
                        onClick={() => setFilterWorkOrderId('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Asset */}
                  <div className="relative z-[59]">
                    <LinkField
                      label="Asset"
                      doctype="Asset"
                      value={filterAsset}
                      onChange={(val) => setFilterAsset(val)}
                      placeholder="Select Asset"
                      disabled={false}
                      compact={true}
                    />
                    {filterAsset && (
                      // <button
                      //   onClick={() => setFilterAsset('')}
                      //   className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      // >
                      <button
                        onClick={() => { setFilterAsset(''); searchParams.delete('asset'); setSearchParams(searchParams); }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Type (Issue Type) */}
                  <div className="relative z-[58]">
                    <LinkField
                      label="Type"
                      doctype="Issue Type"
                      value={filterType}
                      onChange={(val) => setFilterType(val)}
                      placeholder="Select Type"
                      disabled={false}
                      compact={true}
                    />
                    {filterType && (
                      <button
                        onClick={() => setFilterType('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Hospital (Company) */}
                  <div className="relative z-[57]">
                    <LinkField
                      label="Hospital"
                      doctype="Company"
                      value={filterCompany}
                      onChange={(val) => setFilterCompany(val)}
                      placeholder="Select Hospital"
                      disabled={false}
                      compact={true}
                      filters={{ domain: 'Healthcare' }}
                    />
                    {filterCompany && (
                      <button
                        onClick={() => setFilterCompany('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Site Name */}
                  <div className="relative z-[56]">
                    <LinkField
                      label="PHCC Site"
                      doctype="Mobile Team Site"
                      value={filterSiteName}
                      onChange={(val) => setFilterSiteName(val)}
                      placeholder="Select Site"
                      disabled={siteLocked}
                      filters={mobileTeamSiteFilters}
                      compact={true}
                    />
                    {filterSiteName && !siteLocked && (
                      <button
                        onClick={() => { setFilterSiteName(''); searchParams.delete('site_name'); setSearchParams(searchParams); }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Status */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Status
                    </label>
                    <select
                      value={filterStatus}
                      onChange={(e) => setFilterStatus(e.target.value)}
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    >
                      <option value="">All Status</option>
                      <option value="Open">Open</option>
                      <option value="Work In Progress">Work In Progress</option>
                      <option value="Pending Review">Pending Review</option>
                      <option value="Completed">Completed</option>
                      <option value="Cancelled">Cancelled</option>
                      <option value="Closed">Closed</option>
                    </select>
                    {filterStatus && (
                      <button
                        onClick={() => setFilterStatus('')}
                        className="absolute right-8 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Serial Number */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Serial Number
                    </label>
                    <input
                      type="text"
                      value={tempSerialNumber}
                      onChange={(e) => handleSerialNumberChange(e.target.value)}
                      onKeyDown={handleKeyPress}
                      placeholder="Type to search..."
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    {tempSerialNumber && tempSerialNumber !== filterSerialNumber && (
                      <span className="absolute right-2 top-6 text-[9px] text-blue-500 animate-pulse">
                        typing...
                      </span>
                    )}
                    {filterSerialNumber && (
                      <button
                        onClick={() => {
                          setFilterSerialNumber('');
                          setTempSerialNumber('');
                        }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Manufacturer */}
                  <div className="relative z-[55]">
                    <LinkField
                      label="Manufacturer"
                      doctype="Manufacturer"
                      value={filterManufacturer}
                      onChange={(val) => setFilterManufacturer(val)}
                      placeholder="Select Manufacturer"
                      disabled={false}
                      compact={true}
                    />
                    {filterManufacturer && (
                      <button
                        onClick={() => setFilterManufacturer('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Supplier */}
                  <div className="relative z-[54]">
                    <LinkField
                      label="Supplier"
                      doctype="Supplier"
                      value={filterSupplier}
                      onChange={(val) => setFilterSupplier(val)}
                      placeholder="Select Supplier"
                      disabled={false}
                      compact={true}
                    />
                    {filterSupplier && (
                      <button
                        onClick={() => setFilterSupplier('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Department */}
                  <div className="relative z-[53]">
                    <LinkField
                      label="Department"
                      doctype="Department"
                      value={filterDepartment}
                      onChange={(val) => setFilterDepartment(val)}
                      placeholder="Select Department"
                      disabled={false}
                      compact={true}
                    />
                    {filterDepartment && (
                      <button
                        onClick={() => setFilterDepartment('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Priority */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Priority
                    </label>
                    <select
                      value={filterPriority}
                      onChange={(e) => setFilterPriority(e.target.value)}
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    >
                      <option value="">All Priorities</option>
                      <option value="Normal">Normal</option>
                      <option value="Urgent">Urgent</option>
                    </select>
                    {filterPriority && (
                      <button
                        onClick={() => setFilterPriority('')}
                        className="absolute right-8 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Save Filter Modal */}
      {showSaveFilterModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[70] p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6 animate-scale-in">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Save Filter Preset
            </h3>
            <input
              type="text"
              value={filterPresetName}
              onChange={(e) => setFilterPresetName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  handleSaveFilterPreset();
                }
              }}
              placeholder="Enter filter name (e.g., 'Pending High Priority')"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white mb-4"
              autoFocus
            />
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => {
                  setShowSaveFilterModal(false);
                  setFilterPresetName('');
                }}
                className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveFilterPreset}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md transition-colors flex items-center gap-2"
              >
                <FaSave size={12} />
                Save Filter
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Export Modal */}
      <ExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        selectedCount={selectedRows.size}
        totalCount={totalCount}
        pageCount={workOrders.length}
        onExport={handleExport}
        isExporting={isExporting}
        exportColumns={EXPORT_COLUMNS}
      />

      {/* Work Orders Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden relative">
        {/* Inline loading overlay */}
        {loading && initialLoadComplete && (
          <div className="absolute inset-0 bg-white/60 dark:bg-gray-800/60 flex items-center justify-center z-10 backdrop-blur-[1px]">
            <div className="flex items-center gap-3 bg-white dark:bg-gray-700 px-4 py-2 rounded-lg shadow-lg">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500"></div>
              <span className="text-sm text-gray-600 dark:text-gray-300">Filtering...</span>
            </div>
          </div>
        )}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-100 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
              <tr>
                {/* Select All Checkbox */}
                <th className="px-4 py-3 text-left">
                  <button
                    onClick={handleSelectAll}
                    className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                    title={isAllSelected ? "Deselect all" : "Select all"}
                  >
                    {isAllSelected ? (
                      <FaCheckSquare className="text-blue-600 dark:text-blue-400" size={18} />
                    ) : isSomeSelected ? (
                      <div className="relative">
                        <FaSquare size={18} />
                        <div className="absolute inset-0 flex items-center justify-center">
                          <div className="w-2 h-0.5 bg-current"></div>
                        </div>
                      </div>
                    ) : (
                      <FaSquare size={18} />
                    )}
                  </button>
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Work Order ID
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Asset
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Type
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Department
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Priority
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {workOrders.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                    <div className="flex flex-col items-center">
                      <FaSearch className="text-4xl text-gray-300 dark:text-gray-600 mb-2" />
                      <p>No work orders found</p>
                      {hasActiveFilters ? (
                        <button
                          onClick={handleClearFilters}
                          className="mt-4 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                        >
                          Clear filters
                        </button>
                      ) : (
                        <button
                          onClick={handleCreateNew}
                          className="mt-4 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                        >
                          Create your first work order
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ) : (
                workOrders.map((workOrder) => (
                  <tr 
                    key={workOrder.name} 
                    className={`hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer ${
                      selectedRows.has(workOrder.name) ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                    }`}
                    onClick={() => handleView(workOrder.name)}
                  >
                    {/* Row Checkbox */}
                    <td className="px-4 py-4" onClick={(e) => e.stopPropagation()}>
                      <button
                        onClick={() => handleSelectRow(workOrder.name)}
                        className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                      >
                        {selectedRows.has(workOrder.name) ? (
                          <FaCheckSquare className="text-blue-600 dark:text-blue-400" size={18} />
                        ) : (
                          <FaSquare size={18} />
                        )}
                      </button>
                    </td>
                    {/* <td className="px-6 py-4 whitespace-nowrap">
                      <div className="font-medium text-gray-900 dark:text-white">{workOrder.name}</div>
                      <div className="text-sm text-gray-500 dark:text-gray-400">
                        {workOrder.creation ? new Date(workOrder.creation).toLocaleDateString() : ''}
                      </div>
                    </td> */}

                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="font-medium text-gray-900 dark:text-white">{workOrder.name}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">
                        {formatDate(workOrder.modified)}
                      </div>
                    </td>
                    
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-white">{workOrder.asset_name || '-'}</div>
                      <div className="text-xs text-gray-500 dark:text-gray-400">{workOrder.asset || ''}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {workOrder.work_order_type || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {workOrder.department || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(workOrder.repair_status || '')}
                        <span className={`px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(workOrder.repair_status || '')}`}>
                          {workOrder.repair_status || 'Unknown'}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getPriorityColor(workOrder.custom_priority_ || '')}`}>
                        {workOrder.custom_priority_ || 'Normal'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                        <button
                          onClick={() => handleView(workOrder.name)}
                          className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 p-2 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors"
                          title="View Details"
                        >
                          <FaEye />
                        </button>
                        <button
                          onClick={() => handleEdit(workOrder.name)}
                          className="text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300 p-2 hover:bg-green-50 dark:hover:bg-green-900/30 rounded transition-colors"
                          title="Edit Work Order"
                        >
                          <FaEdit />
                        </button>
                        <button
                          onClick={() => handleDuplicate(workOrder.name)}
                          className="text-purple-600 dark:text-purple-400 hover:text-purple-900 dark:hover:text-purple-300 p-2 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded transition-colors"
                          title="Duplicate Work Order"
                        >
                          <FaCopy />
                        </button>
                        <button
                          onClick={() => setDeleteConfirmOpen(workOrder.name)}
                          className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 p-2 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors"
                          title="Delete Work Order"
                          disabled={mutationLoading}
                        >
                          <FaTrash />
                        </button>
                        
                        {/* More Actions Dropdown */}
                        <div className="relative" ref={actionMenuOpen === workOrder.name ? dropdownRef : null}>
                          <button
                            onClick={() => setActionMenuOpen(actionMenuOpen === workOrder.name ? null : workOrder.name)}
                            className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded transition-colors"
                            title="More Actions"
                          >
                            <FaEllipsisV />
                          </button>
                          
                          {actionMenuOpen === workOrder.name && (
                            <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
                              {/* <button
                                onClick={() => {
                                  handleExportSingle(workOrder);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2 rounded-t-lg"
                              >
                                <FaDownload className="text-blue-500" />
                                Export as JSON
                              </button> */}
                              <button
                                onClick={() => {
                                  handlePrint(workOrder.name);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2 rounded-b-lg"
                              >
                                <FaPrint className="text-purple-500" />
                                Print Work Order
                              </button>
                            </div>
                          )}
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <ListPagination
          currentPage={page + 1}
          totalCount={totalCount}
          pageSize={limit}
          hasMore={hasMore}
          itemLabel={t('pagination.workOrders')}
          onPageChange={(p) => setPage(Math.max(0, p - 1))}
        />
      </div>

      {/* Delete Confirmation Modal */}
      {deleteConfirmOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 shadow-2xl">
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0 w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <FaTrash className="text-red-600 dark:text-red-400 text-xl" />
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  Delete Work Order
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  Are you sure you want to delete this work order? This action cannot be undone.
                </p>
                <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md p-3 mb-4">
                  <p className="text-xs text-yellow-800 dark:text-yellow-300">
                    <strong>Work Order ID:</strong> {deleteConfirmOpen}
                  </p>
                </div>
                <div className="flex gap-3 justify-end">
                  <button
                    onClick={() => setDeleteConfirmOpen(null)}
                    className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
                    disabled={mutationLoading}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={() => handleDelete(deleteConfirmOpen)}
                    className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                    disabled={mutationLoading}
                  >
                    {mutationLoading ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                        Deleting...
                      </>
                    ) : (
                      <>
                        <FaTrash />
                        Delete Work Order
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @keyframes scale-in {
          from {
            transform: scale(0.95);
            opacity: 0;
          }
          to {
            transform: scale(1);
            opacity: 1;
          }
        }
        .animate-scale-in {
          animation: scale-in 0.2s ease-out;
        }
        
        .scrollbar-hide {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </div>
  );
};

export default WorkOrderList;