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 { useTechnicianFilter } from '../hooks/useTechnicianFilter';
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 , FaTable,
  FaLock, FaSpinner
} from 'react-icons/fa';
import LinkField from '../components/LinkField';
import ListPagination from '../components/ListPagination';
import { buildDateRangeFilters, toFrappeFilterArray } from '../utils/listFilterUtils';
import { useUserPermissions } from '../hooks/useUserPermissions';
import WorkOrderReportModal from '../components/WorkOrderReportModal';
import DeleteRequestButton from '../components/DeleteRequestButton';
import type { DeleteStatus } from '../services/deleteRequestService';
import apiService from '../services/apiService';
import API_CONFIG from '../config/api';
import DynamicExportModal from '../components/DynamicExportModal';
import VoiceStatusModal from '../components/VoiceStatusModal';
import { FaMicrophone } from 'react-icons/fa';

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

// ✅ Civil Work Category — Select field options
const CIVIL_WORK_CATEGORY_OPTIONS = ['CARPENTARY', 'MASONRY', 'PAINTING', 'PLUMPING'];

// ✅ The Issue Type value that triggers the Civil Work Category filter
const CIVIL_ISSUE_TYPE = 'Civil works-الأعمال المدنية';

interface SelectedWorkOrderInfo {
  name: string;
  workflow_state: string;
  repair_status: string;
}

interface CloseConfirmModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedWorkOrders: SelectedWorkOrderInfo[];
  onConfirmClose: () => void;
  isClosing: boolean;
}

const CloseConfirmModal: React.FC<CloseConfirmModalProps> = ({
  isOpen, onClose, selectedWorkOrders, onConfirmClose, isClosing
}) => {
  const { t } = useTranslation();
  if (!isOpen) return null;

  const getStatusColor = (status: string) => {
    switch (status?.toLowerCase()) {
      case 'closed': return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300';
      case 'completed': return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';
      case 'in progress': case 'work in progress': case 'repair inprogress':
        return 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300';
      case 'pending': case 'pending approval': case 'pending review': 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-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-300';
    }
  };

  const alreadyClosedCount = selectedWorkOrders.filter(wo => wo.workflow_state?.toLowerCase() === 'closed').length;
  const canCloseCount = selectedWorkOrders.length - alreadyClosedCount;

  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">
        <div className="bg-gradient-to-r from-orange-500 to-orange-600 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FaLock className="text-white text-xl" />
              <h3 className="text-lg font-semibold text-white">{t('workOrders.closeModal.title')}</h3>
            </div>
            <button onClick={onClose} className="text-white/80 hover:text-white transition-colors" disabled={isClosing}>
              <FaTimes size={20} />
            </button>
          </div>
        </div>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
          <div className="mb-4 p-4 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg">
            <div className="flex items-start gap-3">
              <FaExclamationTriangle className="text-orange-500 mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-sm font-medium text-orange-800 dark:text-orange-200">{t('workOrders.closeModal.confirmBulkClose')}</p>
                <p className="text-xs text-orange-600 dark:text-orange-400 mt-1">{t('workOrders.closeModal.aboutToClose', { count: canCloseCount })}</p>
                {alreadyClosedCount > 0 && (
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">{t('workOrders.closeModal.alreadyClosedNote', { count: alreadyClosedCount })}</p>
                )}
              </div>
            </div>
          </div>

          <div className="mb-4">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              {t('workOrders.closeModal.selectedWorkOrders', { count: selectedWorkOrders.length })}
            </h4>
            <div className="max-h-64 overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-lg">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 dark:bg-gray-700 sticky top-0">
                  <tr>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('workOrders.closeModal.workOrderId')}</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('workOrders.closeModal.currentStatus')}</th>
                    <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">{t('workOrders.closeModal.workflowState')}</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {selectedWorkOrders.map((wo) => {
                    const isAlreadyClosed = wo.workflow_state?.toLowerCase() === 'closed';
                    return (
                      <tr key={wo.name} className={`${isAlreadyClosed ? 'bg-gray-50 dark:bg-gray-700/50 opacity-60' : 'bg-white dark:bg-gray-800'}`}>
                        <td className="px-4 py-3">
                          <span className="font-medium text-gray-900 dark:text-white">{wo.name}</span>
                          {isAlreadyClosed && <span className="ml-2 text-xs text-gray-500">{t('workOrders.closeModal.alreadyClosed')}</span>}
                        </td>
                        <td className="px-4 py-3">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(wo.repair_status)}`}>{wo.repair_status || 'Open'}</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <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">
            {canCloseCount > 0
              ? <span>{t('workOrders.closeModal.willClose', { count: canCloseCount })}</span>
              : <span className="text-orange-600 dark:text-orange-400">{t('workOrders.closeModal.allAlreadyClosed')}</span>}
          </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={isClosing}>
              {t('workOrders.closeModal.cancel')}
            </button>
            <button onClick={onConfirmClose} disabled={canCloseCount === 0 || isClosing}
              className="px-4 py-2 text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
              {isClosing
                ? <><FaSpinner className="animate-spin" size={14} />{t('workOrders.closeModal.closing')}</>
                : <><FaLock size={14} />{t('workOrders.closeModal.close')} {canCloseCount > 0 ? `(${canCloseCount})` : ''}</>}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};


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

  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) => {
    setSearchParamsRef.current((prev) => {
      const next = new URLSearchParams(prev);
      next.set('page', String(zeroBasedPage + 1));
      return next;
    });
  }, []);

  useEffect(() => {
    setSearchParamsRef.current = setSearchParams;
  }, [setSearchParams]);

  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const limit = 20;

  const assetFromUrl = searchParams.get('asset');
  const isFilteredFromAsset = !!assetFromUrl;
  const workOrderTypeFromUrl = searchParams.get('work_order_type');
  const isFilteredFromWorkOrderType = !!workOrderTypeFromUrl;

  const [initialLoadComplete, setInitialLoadComplete] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());
  const [showExportModal, setShowExportModal] = useState(false);
  const [showReportModal, setShowReportModal] = useState(false);
  const [showCloseModal, setShowCloseModal] = useState(false);
  const [showVoiceModal, setShowVoiceModal] = useState(false);
  const [isClosing, setIsClosing] = useState(false);
  const [selectedWorkOrdersInfo, setSelectedWorkOrdersInfo] = useState<SelectedWorkOrderInfo[]>([]);
  const [isClusterManager, setIsClusterManager] = useState(false);
  const [isEndUserOnly, setIsEndUserOnly] = useState(false);
  const [currentUserEmail, setCurrentUserEmail] = useState('');
  const canRequestDelete = !isEndUserOnly;
  const [userRoles, setUserRoles] = useState<string[]>([]);
  const [listIsSystemManager, setListIsSystemManager] = useState(false);

  const { permissionFilters, loading: permissionsLoading, error: permissionsError, hasAnyRestrictions } = useUserPermissions('Work_Order');
  const { technicianOrFilters, isTechnicianOnly, loading: technicianFilterLoading, error: technicianFilterError } = useTechnicianFilter();

  const DELETE_ALLOWED_ROLES = ['System Manager', 'Cluster Manager', 'Contractor Supervisor', 'Contractor Manager', 'Work Control'];
  const ADD_WORK_ORDER_ALLOWED_ROLES = ['System Manager', 'Cluster Manager', 'Work Control', 'End user'];
  const WO_REPORT_ALLOWED_ROLES = ['System Manager', 'Maintenance Manager', 'Work Control', 'Technician', 'Contractor Supervisor', 'Contractor Manager', 'Contractor Engineer'];
  const CLOSE_ALLOWED_ROLES = ['Cluster Manager'];

  const [canDelete, setCanDelete] = useState(false);
  const [canAddWorkOrder, setCanAddWorkOrder] = useState(false);
  const [canViewWOReport, setCanViewWOReport] = useState(false);

  useEffect(() => {
    const checkPermissions = async () => {
      try {
        const [deleteRes, addRes, woReportRes, closeRes, userRes] = await Promise.all([
          fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ roles: DELETE_ALLOWED_ROLES.join(',') })
          }),
          fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ roles: ADD_WORK_ORDER_ALLOWED_ROLES.join(',') })
          }),
          fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ roles: WO_REPORT_ALLOWED_ROLES.join(',') })
          }),
          fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ roles: CLOSE_ALLOWED_ROLES.join(',') })
          }),
          fetch('/api/method/frappe.auth.get_logged_user', { credentials: 'include' })
        ]);

        const [deleteData, addData, woReportData, closeData, userData] = await Promise.all([
          deleteRes.json(), addRes.json(), woReportRes.json(), closeRes.json(), userRes.json()
        ]);

        if (deleteData.message) setCanDelete(deleteData.message.has_role);
        if (addData.message) setCanAddWorkOrder(addData.message.has_role);
        if (woReportData.message) setCanViewWOReport(woReportData.message.has_role);
        if (closeData.message) setIsClusterManager(closeData.message.has_role);

        const userEmail = userData.message || '';
        setCurrentUserEmail(userEmail);

        // Fetch full roles list
        const rolesListRes = await fetch('/api/method/asset_lite.api.user_roles.get_user_roles', { credentials: 'include' });
        const rolesListData = await rolesListRes.json();
        const rolesList = Array.isArray(rolesListData.message) ? rolesListData.message : [];
        setUserRoles(rolesList);
        const isSystemMgr = rolesList.includes('System Manager');
        setListIsSystemManager(isSystemMgr);

        // Check End User only
        const END_USER_PRIVILEGED_ROLES = ['System Manager', 'Cluster Manager', 'Maintenance Manager', 'Work Control', 'Technician', 'Contractor Supervisor', 'Contractor Manager', 'Contractor Engineer'];
        const privilegedRes = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ roles: END_USER_PRIVILEGED_ROLES.join(',') })
        });
        const privilegedData = await privilegedRes.json();
        if (privilegedData.message) setIsEndUserOnly(!privilegedData.message.has_role);

      } catch (error) {
        console.error('Error checking permissions:', error);
        setCanDelete(false);
        setCanAddWorkOrder(false);
        setCanViewWOReport(false);
        setIsClusterManager(false);
        setIsEndUserOnly(false);
      }
    };

    checkPermissions();
  }, []);

  // Filter states (init from URL)
  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 [filterWorkOrderId, setFilterWorkOrderId] = useState(() => searchParams.get('work_order_id') || '');
  const [filterAsset, setFilterAsset] = useState(() => searchParams.get('asset') || '');
  const [filterType, setFilterType] = useState(() => searchParams.get('work_order_type') || '');
  // ✅ Civil Work Category filter — only active when filterType === CIVIL_ISSUE_TYPE
  const [filterCivilWorkCategory, setFilterCivilWorkCategory] = useState(() => searchParams.get('civil_work_category') || '');
  const [filterCompany, setFilterCompany] = useState(() => searchParams.get('company') || '');
  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 [filterWorkflowState, setFilterWorkflowState] = useState(() => searchParams.get('workflow_state') || '');

  // ✅ Derived: show civil category filter only when type is Civil works
  const isCivilTypeSelected = filterType === CIVIL_ISSUE_TYPE;

  const sortOptions = ['creation desc', 'creation asc', 'modified desc', 'modified asc', 'name asc', 'name desc'] as const;
  const [sortBy, setSortBy] = useState<string>(() => searchParams.get('sort_by') || 'modified desc');

  const [isFilterExpanded, setIsFilterExpanded] = useState(true);
  const [activeFilterCount, setActiveFilterCount] = useState(0);
  const [savedFilters, setSavedFilters] = useState<any[]>([]);
  const [showSaveFilterModal, setShowSaveFilterModal] = useState(false);
  const [filterPresetName, setFilterPresetName] = useState('');
  const [tempSerialNumber, setTempSerialNumber] = useState(() => searchParams.get('serial_number') || '');
  const serialNumberDebounceRef = useRef<number | null>(null);

  useEffect(() => {
    const saved = localStorage.getItem('workOrderFilterPresets');
    if (saved) setSavedFilters(JSON.parse(saved));
  }, []);

  const hasDateFilter = dateFilterBy && (dateStart || dateEnd);

  // Active filter count — civil_work_category only counted when civil type is selected
  useEffect(() => {
    const count = [
      filterWorkOrderId, filterAsset, filterType,
      isCivilTypeSelected ? filterCivilWorkCategory : '',
      filterCompany, filterStatus, filterSerialNumber,
      filterManufacturer, filterSupplier, filterDepartment, filterPriority, filterWorkflowState
    ].filter(Boolean).length + (hasDateFilter ? 1 : 0);
    setActiveFilterCount(count);
  }, [hasDateFilter, filterWorkOrderId, filterAsset, filterType, isCivilTypeSelected, filterCivilWorkCategory,
      filterCompany, filterStatus, filterSerialNumber, filterManufacturer, filterSupplier,
      filterDepartment, filterPriority, filterWorkflowState]);

  // Build filters object for API
  const filters: Record<string, any> = {};
  if (filterWorkOrderId) filters['name'] = filterWorkOrderId;
  if (filterAsset) filters['asset'] = filterAsset;
  if (filterType) filters['work_order_type'] = filterType;
  // ✅ civil_work_category filter only applied when civil type is selected
  if (isCivilTypeSelected && filterCivilWorkCategory) filters['custom_civil_work_category'] = filterCivilWorkCategory;
  if (filterCompany) filters['company'] = filterCompany;
  if (filterStatus) filters['repair_status'] = 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;
  if (filterWorkflowState) filters['workflow_state'] = filterWorkflowState;
  Object.assign(filters, buildDateRangeFilters(dateFilterBy, dateStart, dateEnd));
  filters['custom_delete_status'] = ['!=', 'Deleted'];
  if (isEndUserOnly && currentUserEmail) filters['owner'] = currentUserEmail;

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

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

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

  // Track if we ever had a successful load — once true, never show the full-page error screen
  const hadSuccessfulLoad = useRef(false);

  useEffect(() => {
    if (!loading && !permissionsLoading && !technicianFilterLoading) {
      if (!error) hadSuccessfulLoad.current = true;
      if (!initialLoadComplete) setInitialLoadComplete(true);
    }
  }, [loading, initialLoadComplete, permissionsLoading, technicianFilterLoading, error]);

  // Sync filters to URL
  const filtersChangedOnce = useRef(false);
  useEffect(() => {
    if (!filtersChangedOnce.current) { filtersChangedOnce.current = true; return; }
    setSearchParamsRef.current((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');
      // ✅ Only persist civil filter in URL when civil type is selected
      if (isCivilTypeSelected && filterCivilWorkCategory) next.set('civil_work_category', filterCivilWorkCategory);
      else next.delete('civil_work_category');
      if (filterCompany) next.set('company', filterCompany); else next.delete('company');
      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 (filterWorkflowState) next.set('workflow_state', filterWorkflowState); else next.delete('workflow_state');
      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,
      isCivilTypeSelected, filterCivilWorkCategory,
      filterCompany, filterStatus, filterSerialNumber, filterManufacturer,
      filterSupplier, filterDepartment, filterPriority, filterWorkflowState, sortBy]);

  // Clear civil category filter when type is changed away from civil
  useEffect(() => {
    if (!isCivilTypeSelected) {
      setFilterCivilWorkCategory('');
    }
  }, [isCivilTypeSelected]);

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

  const handleSerialNumberChange = (value: string) => {
    setTempSerialNumber(value);
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
    serialNumberDebounceRef.current = window.setTimeout(() => setFilterSerialNumber(value), 800);
  };

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

  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,
        filterCivilWorkCategory,
        filterCompany, filterStatus, filterSerialNumber,
        filterManufacturer, filterSupplier, filterDepartment, filterPriority, filterWorkflowState
      }
    };
    const updated = [...savedFilters, preset];
    setSavedFilters(updated);
    setFilterPresetName('');
    setShowSaveFilterModal(false);
    localStorage.setItem('workOrderFilterPresets', JSON.stringify(updated));
  };

  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 || '');
    setFilterCivilWorkCategory(f.filterCivilWorkCategory || '');
    setFilterCompany(f.filterCompany || '');
    setFilterStatus(f.filterStatus || '');
    setFilterSerialNumber(f.filterSerialNumber || '');
    setTempSerialNumber(f.filterSerialNumber || '');
    setFilterManufacturer(f.filterManufacturer || '');
    setFilterSupplier(f.filterSupplier || '');
    setFilterDepartment(f.filterDepartment || '');
    setFilterPriority(f.filterPriority || '');
    setFilterWorkflowState(f.filterWorkflowState || '');
  };

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

  useEffect(() => {
    return () => { if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current); };
  }, []);

  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]);

  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;

  // const fetchAllWorkOrdersForExport = useCallback(async (): Promise<any[]> => {
  //   const allWorkOrders: any[] = [];
  //   let currentPage = 0;
  //   const pageSize = 100;
  //   let hasMoreData = true;
  //   while (hasMoreData) {
  //     try {
  //       const requestBody: any = {
  //         doctype: 'Work_Order',
  //         filters: { ...filters, ...permissionFilters },
  //         fields: ['*'],
  //         limit_start: currentPage * pageSize,
  //         limit_page_length: pageSize,
  //         order_by: 'creation desc'
  //       };
  //       if (technicianOrFilters && technicianOrFilters.length > 0) requestBody.or_filters = technicianOrFilters;
  //       const response = await fetch('/api/method/frappe.client.get_list', {
  //         method: 'POST', headers: { 'Content-Type': 'application/json' },
  //         body: JSON.stringify(requestBody)
  //       });
  //       const data = await response.json();
  //       const results = data.message || [];
  //       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;
  // }, [filters, permissionFilters, technicianOrFilters]);


  const fetchAllWorkOrdersForExport = useCallback(async (): Promise<any[]> => {
    const allWorkOrders: any[] = [];
    let currentPage = 0;
    const pageSize = 100;
    let hasMoreData = true;

    // ✅ Use toFrappeFilterArray to properly convert creation_from/creation_to (date range)
    // and other filter types to Frappe's format. The custom conversion was incorrectly
    // treating creation_from/creation_to as doctype fields, causing "no data found" on export.
    const mergedFilters = { ...filters, ...permissionFilters };
    const filterArrays = toFrappeFilterArray(mergedFilters);

    while (hasMoreData) {
      try {
        const requestBody: any = {
          doctype: 'Work_Order',
          filters: filterArrays.length > 0 ? filterArrays : {},
          fields: ['*'],
          limit_start: currentPage * pageSize,
          limit_page_length: pageSize,
          order_by: 'creation desc',
        };

        if (technicianOrFilters && technicianOrFilters.length > 0) {
          requestBody.or_filters = technicianOrFilters;
        }

        const response = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestBody),
        });

        const data = await response.json();
        const results: any[] = data.message || [];
        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;
  }, [filters, permissionFilters, technicianOrFilters]);

  const handleOpenCloseModal = () => {
    const selectedInfo: SelectedWorkOrderInfo[] = workOrders
      .filter(wo => selectedRows.has(wo.name))
      .map(wo => ({ name: wo.name, workflow_state: wo.workflow_state || 'Draft', repair_status: wo.repair_status || 'Open' }));
    setSelectedWorkOrdersInfo(selectedInfo);
    setShowCloseModal(true);
  };

  const handleBulkClose = async () => {
    setIsClosing(true);
    const workOrdersToClose = selectedWorkOrdersInfo.filter(wo => wo.workflow_state?.toLowerCase() !== 'closed');
    let successCount = 0; let failCount = 0; const failedWorkOrders: string[] = [];
    for (const wo of workOrdersToClose) {
      try {
        const response = await fetch('/api/method/frappe.model.workflow.apply_workflow', {
          method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
          body: JSON.stringify({ doc: { doctype: 'Work_Order', name: wo.name }, action: 'Close' })
        });
        const result = await response.json();
        if (result.exc || result.exception) throw new Error(result.exc || result.exception);
        successCount++;
      } catch (error) {
        console.error(`Failed to close ${wo.name}:`, error);
        failCount++;
        failedWorkOrders.push(wo.name);
      }
    }
    setIsClosing(false); setShowCloseModal(false); setSelectedRows(new Set()); refetch();
    if (successCount > 0 && failCount === 0) alert(`Successfully closed ${successCount} work order${successCount !== 1 ? 's' : ''}.`);
    else if (successCount > 0 && failCount > 0) alert(`Closed ${successCount} work order${successCount !== 1 ? 's' : ''}. Failed to close ${failCount}: ${failedWorkOrders.join(', ')}`);
    else if (failCount > 0) alert(`Failed to close work orders: ${failedWorkOrders.join(', ')}`);
  };

  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 PRINT_FORMAT_NAME = 'Service_Report';
  const handlePrint = (workOrderName: string) => {
    const baseUrl = API_CONFIG.BASE_URL || '';
    const printUrl = `${baseUrl}/printview?doctype=Work_Order&name=${encodeURIComponent(workOrderName)}&format=${encodeURIComponent(PRINT_FORMAT_NAME)}&trigger_print=1`;
    window.open(printUrl, '_blank');
  };

  const handleClearFilters = () => {
    setDateFilterBy(''); setDateStart(''); setDateEnd('');
    setSortBy('modified desc');
    setFilterWorkOrderId(''); setFilterAsset(''); setFilterType('');
    setFilterCivilWorkCategory('');
    setFilterCompany(''); setFilterStatus('');
    setFilterSerialNumber(''); setTempSerialNumber('');
    setFilterManufacturer(''); setFilterSupplier('');
    setFilterDepartment(''); setFilterPriority(''); setFilterWorkflowState('');
    setSearchParamsRef.current((prev) => {
      const next = new URLSearchParams(prev);
      next.delete('date_filter_by'); next.delete('date_start'); next.delete('date_end');
      next.delete('work_order_id'); next.delete('asset'); next.delete('work_order_type');
      next.delete('civil_work_category');
      next.delete('company'); next.delete('status'); next.delete('serial_number');
      next.delete('manufacturer'); next.delete('supplier'); next.delete('department');
      next.delete('priority'); next.delete('workflow_state');
      next.set('page', '1');
      return next;
    });
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
  };

  const hasActiveFilters = hasDateFilter || filterWorkOrderId || filterAsset || filterType ||
    (isCivilTypeSelected && filterCivilWorkCategory) ||
    filterCompany || filterStatus || filterSerialNumber ||
    filterManufacturer || filterSupplier || filterDepartment || filterPriority || filterWorkflowState;

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

  const getDeleteStatusRowClass = (deleteStatus: string | undefined): string => {
    switch (deleteStatus) {
      case 'Delete Request With Supervisor': return 'bg-orange-50 dark:bg-orange-900/10';
      case 'Delete Request With CM': return 'bg-yellow-50 dark:bg-yellow-900/10';
      case 'Deleted': return 'bg-red-50 dark:bg-red-900/10';
      default: return '';
    }
  };

  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 getWorkflowStateColor = (state: string) => {
    switch (state?.toLowerCase()) {
      case 'closed': return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300';
      case 'completed': return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';
      case 'work in progress': case 'repair inprogress': return 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300';
      case 'pending review': case 'pending approval': case 'sent to engineer': return 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300';
      case 'open': case 'draft': 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-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-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';
    }
  };

  if ((permissionsLoading || technicianFilterLoading) && !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">{t('assets.loadingPermissions')}</p>
        </div>
      </div>
    );
  }

  if (permissionsError || technicianFilterError) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <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 || technicianFilterError}</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>
    );
  }

  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">{t('workOrders.loadingWorkOrders')}</p>
        </div>
      </div>
    );
  }

  if (error && initialLoadComplete && !hadSuccessfulLoad.current) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <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-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-800 dark:text-white">{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>}
            {isTechnicianOnly && <span className="ml-2 text-amber-600 dark:text-amber-400">• Showing your assigned work orders</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">
          {canViewWOReport && (
            <button
              onClick={() => setShowVoiceModal(true)}
              className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all"
              title="Use this to bulk update work order status"
            >
              <FaMicrophone />
              <span className="font-medium">Voice Command Assist</span>
            </button>
          )}
          {isClusterManager && selectedRows.size > 0 && (
            <button onClick={handleOpenCloseModal} className="bg-orange-600 hover:bg-orange-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all">
              <FaLock /><span className="font-medium">Close</span>
              <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">{selectedRows.size}</span>
            </button>
          )}
          <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>
          {canAddWorkOrder && (
            <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">
        <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">
            <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>

            {/* Active Filter Chips */}
            {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(''); 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(''); searchParams.delete('work_order_type'); setSearchParams(searchParams); }} className="hover:text-red-500 transition-colors"><FaTimes className="text-[9px]" /></button>
                    </span>
                  )}
                  {/* ✅ Civil Work Category chip — only rendered when civil type is selected */}
                  {isCivilTypeSelected && filterCivilWorkCategory && (
                    <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">Civil Category:</span> {filterCivilWorkCategory}
                      <button onClick={(e) => { e.stopPropagation(); setFilterCivilWorkCategory(''); searchParams.delete('civil_work_category'); setSearchParams(searchParams); }} 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>
                  )}
                  {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>
                  )}
                  {filterWorkflowState && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-violet-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Workflow:</span> {filterWorkflowState}
                      <button onClick={(e) => { e.stopPropagation(); setFilterWorkflowState(''); searchParams.delete('workflow_state'); setSearchParams(searchParams); }} 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>
            )}

            <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">
            {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>
            )}

            <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">

                  {/* Sort By */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.sortBy')}</label>
                    <select value={sortBy} onChange={(e) => setSortBy(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="creation desc">{t('filters.sortCreationNewest')}</option>
                      <option value="creation asc">{t('filters.sortCreationOldest')}</option>
                      <option value="modified desc">{t('filters.sortModifiedNewest')}</option>
                      <option value="modified asc">{t('filters.sortModifiedOldest')}</option>
                      <option value="name asc">{t('filters.sortNameAsc')}</option>
                      <option value="name desc">{t('filters.sortNameDesc')}</option>
                    </select>
                  </div>

                  {/* Date Filter By */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.filterBy')}</label>
                    <select value={dateFilterBy} onChange={(e) => { const v = e.target.value as '' | 'creation' | 'modified'; setDateFilterBy(v); }} 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="">{t('filters.filterBy')}</option>
                      <option value="creation">{t('filters.createdDate')}</option>
                      <option value="modified">{t('filters.latestModifiedDate')}</option>
                    </select>
                  </div>
                  {dateFilterBy && (
                    <>
                      <div className="relative">
                        <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.startDate')}</label>
                        <input type="date" value={dateStart} onChange={(e) => { const v = e.target.value; setDateStart(v); if (dateEnd && v > dateEnd) setDateEnd(v); }} 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" />
                      </div>
                      <div className="relative">
                        <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.endDate')}</label>
                        <input type="date" value={dateEnd} onChange={(e) => setDateEnd(e.target.value)} min={dateStart || undefined} 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" />
                      </div>
                    </>
                  )}

                  {/* Work Order ID */}
                  <div className="relative z-[60]">
                    <LinkField label={t('filters.workOrderId')} doctype="Work_Order" value={filterWorkOrderId} onChange={(val) => setFilterWorkOrderId(val)} placeholder={t('linkField.selectLabel', { label: t('filters.workOrderId') })} disabled={false} compact={true} filters={{ custom_delete_status: ['!=', 'Deleted'] }} />
                    {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={t('filters.asset')} doctype="Asset" value={filterAsset} onChange={(val) => setFilterAsset(val)} placeholder={t('linkField.selectLabel', { label: t('filters.asset') })} disabled={false} compact={true} filters={{ custom_delete_status: ['!=', 'Deleted'] }} />
                    {filterAsset && <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={t('filters.type')} doctype="Issue Type" value={filterType}
                      onChange={(val) => { setFilterType(val); if (searchParams.has('work_order_type')) { searchParams.delete('work_order_type'); setSearchParams(searchParams); } }}
                      placeholder={t('linkField.selectLabel', { label: t('filters.type') })} disabled={false} compact={true}
                    />
                    {filterType && <button onClick={() => { setFilterType(''); searchParams.delete('work_order_type'); setSearchParams(searchParams); }} className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"><FaTimes size={10} /></button>}
                  </div>

                  {/* ✅ Civil Work Category — shown only when Type = CIVIL_ISSUE_TYPE */}
                  {isCivilTypeSelected && (
                    <div className="relative">
                      <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                        Civil Work Category
                      </label>
                      <select
                        value={filterCivilWorkCategory}
                        onChange={(e) => setFilterCivilWorkCategory(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 Civil Categories</option>
                        {CIVIL_WORK_CATEGORY_OPTIONS.map((opt) => (
                          <option key={opt} value={opt}>{opt}</option>
                        ))}
                      </select>
                      {filterCivilWorkCategory && (
                        <button
                          onClick={() => setFilterCivilWorkCategory('')}
                          className="absolute right-8 top-6 text-gray-400 hover:text-red-500 transition-colors"
                        >
                          <FaTimes size={10} />
                        </button>
                      )}
                    </div>
                  )}

                  {/* Hospital (Company) */}
                  <div className="relative z-[57]">
                    <LinkField label={t('filters.hospital')} doctype="Company" value={filterCompany} onChange={(val) => setFilterCompany(val)} placeholder={t('linkField.selectLabel', { label: t('filters.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>

                  {/* Status */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.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="">{t('filters.allStatuses')}</option>
                      <option value="Open">{t('workOrders.status.open')}</option>
                      <option value="Work In Progress">{t('workOrders.status.work_in_progress')}</option>
                      <option value="Pending Review">{t('workOrders.status.pending_review')}</option>
                      <option value="Closed">{t('workOrders.status.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>

                  {/* Workflow State */}
                  <div className="relative z-[56]">
                    <LinkField label={t('filters.workflowState', 'Workflow State')} doctype="Workflow State" value={filterWorkflowState} onChange={(val) => setFilterWorkflowState(val)} placeholder={t('linkField.selectLabel', { label: t('filters.workflowState', 'Workflow State') })} disabled={false} compact={true} />
                    {filterWorkflowState && <button onClick={() => { setFilterWorkflowState(''); searchParams.delete('workflow_state'); setSearchParams(searchParams); }} className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"><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">{t('commonFields.serialNumber')}</label>
                    <input type="text" value={tempSerialNumber} onChange={(e) => handleSerialNumberChange(e.target.value)} onKeyDown={handleKeyPress} placeholder={t('common.typeToSearch')} 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">{t('common.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={t('filters.mfr')} doctype="Manufacturer" value={filterManufacturer} onChange={(val) => setFilterManufacturer(val)} placeholder={t('linkField.selectLabel', { label: t('filters.mfr') })} 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={t('filters.supplier')} doctype="Supplier" value={filterSupplier} onChange={(val) => setFilterSupplier(val)} placeholder={t('linkField.selectLabel', { label: t('filters.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={t('filters.dept')} doctype="Department" value={filterDepartment} onChange={(val) => setFilterDepartment(val)} placeholder={t('linkField.selectLabel', { label: t('filters.dept') })} 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">{t('filters.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="">{t('filters.allPriorities')}</option>
                      <option value="Normal">{t('workOrders.priorityNormal')}</option>
                      <option value="Urgent">{t('workOrders.priorityUrgent')}</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 */}
      <DynamicExportModal
        isOpen={showExportModal} onClose={() => setShowExportModal(false)} doctype="Work_Order"
        selectedCount={selectedRows.size} pageCount={workOrders.length} totalCount={totalCount}
        pageData={workOrders} selectedRows={selectedRows} rowKey="name"
        onFetchAll={fetchAllWorkOrdersForExport} fileNamePrefix="work_orders"
        defaultColumns={['name', 'asset', 'asset_name', 'work_order_type', 'company', 'department', 'repair_status', 'workflow_state', 'custom_priority_', 'creation']}
        hiddenColumns={['docstatus', 'idx', 'amended_from', 'naming_series']}
      />

      {/* Close Confirmation Modal */}
      <CloseConfirmModal isOpen={showCloseModal} onClose={() => setShowCloseModal(false)} selectedWorkOrders={selectedWorkOrdersInfo} onConfirmClose={handleBulkClose} isClosing={isClosing} />

      {/* Work Orders Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden relative">
        {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>
                <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">{t('workOrders.table.workOrderId')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('workOrders.table.asset')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('workOrders.table.type')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('workOrders.table.technicalReport')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('workOrders.table.department')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('commonFields.status')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('workOrders.table.priority')}</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('common.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={10} 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>{t('workOrders.table.noWorkOrdersFound')}</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">{t('common.clearFilters')}</button>
                        : canAddWorkOrder
                          ? <button onClick={handleCreateNew} className="mt-4 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline">{t('workOrders.table.createFirstWorkOrder')}</button>
                          : null}
                    </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' : getDeleteStatusRowClass(workOrder.custom_delete_status ?? undefined)}`}
                    title={workOrder.custom_delete_status ? `Delete Status: ${workOrder.custom_delete_status}` : undefined}
                    onClick={() => handleView(workOrder.name)}
                  >
                    <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-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">
                      <div className="text-sm text-gray-700 dark:text-gray-300 max-w-xs truncate" title={workOrder.actions_performed || ''}>{workOrder.actions_performed || '-'}</div>
                    </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_ ? t(`workOrders.priority.${(workOrder.custom_priority_ as string).toLowerCase()}`, workOrder.custom_priority_) : t('workOrders.priority.normal', '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>
                        <div onClick={(e) => e.stopPropagation()}>
                          <DeleteRequestButton
                            doctype="Work_Order" docname={workOrder.name}
                            currentDeleteStatus={(workOrder.custom_delete_status ?? null) as DeleteStatus}
                            userRoles={userRoles} isSystemManager={listIsSystemManager}
                            triggerMode redirectOnDelete="/work-orders" onStatusChange={() => refetch()}
                          />
                        </div>
                        <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">{t('workOrders.deleteWorkOrder')}</h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{t('workOrders.deleteConfirmMessage')}</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>{t('commonFields.workOrderId')}:</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}>{t('common.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>{t('common.deleting')}</>) : (<><FaTrash />{t('workOrders.deleteWorkOrder')}</>)}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Work Order Report Modal */}
      <WorkOrderReportModal isOpen={showReportModal} onClose={() => setShowReportModal(false)} />
      <VoiceStatusModal
        isOpen={showVoiceModal}
        onClose={() => setShowVoiceModal(false)}
        selectedRows={selectedRows}
        onUpdateSuccess={() => { refetch(); setSelectedRows(new Set()); }}
      />
      <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;