import React, { useState, useMemo, useEffect, useCallback, useRef } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useInspectionList } from '../hooks/useInspection';
import { useUserPermissions } from '../hooks/useUserPermissions'; // ← ADDED
import InspectionReportModal from '../components/InspectionReportModal';
import ListPagination from '../components/ListPagination';
import * as XLSX from 'xlsx';
import { 
  FaPlus, 
  FaFilter, 
  FaSync, 
  FaEye, 
  FaChevronLeft, 
  FaChevronRight,
  FaClipboardCheck,
  FaTimes,
  FaSave,
  FaStar,
  FaTrash,
  FaEdit,
  FaCheckSquare,
  FaSquare,
  FaFileExport,
  FaFileExcel,
  FaFileCsv,
  FaDownload,
  FaExternalLinkAlt
} from 'react-icons/fa';
import LinkField from '../components/LinkField';
import { buildDateRangeFilters, toFrappeFilterArray } from '../utils/listFilterUtils';
import DeleteRequestButton from '../components/DeleteRequestButton';
import type { DeleteStatus } from '../services/deleteRequestService';

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

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

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">
        <div className="bg-gradient-to-r from-teal-500 to-teal-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('inspections.export.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)]">
          {/* Scope Selection */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">{t('inspections.export.selectData')}</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-teal-500 bg-teal-50 dark:bg-teal-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-teal-600 focus:ring-teal-500" />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">{t('inspections.export.selectedRows')}</div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.export.selectedCount', { count: selectedCount })}</div>
                </div>
                {selectedCount > 0 && <span className="bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-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-teal-500 bg-teal-50 dark:bg-teal-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-teal-600 focus:ring-teal-500" />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">{t('inspections.export.currentPage')}</div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.export.currentPageCount', { count: pageCount })}</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-teal-500 bg-teal-50 dark:bg-teal-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-teal-600 focus:ring-teal-500" />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">{t('inspections.export.allWithFilters')}</div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.export.allWithFiltersCount', { count: totalCount })}</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>

          {/* Format Selection */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">{t('inspections.export.exportFormat')}</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-teal-500 bg-teal-50 dark:bg-teal-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-teal-600 focus:ring-teal-500" />
                <FaFileCsv className="text-teal-600 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">{t('inspections.export.csv')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{t('inspections.export.csvDesc')}</div>
                </div>
              </label>
              <label className={`flex-1 flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${format === 'excel' ? 'border-teal-500 bg-teal-50 dark:bg-teal-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-teal-600 focus:ring-teal-500" />
                <FaFileExcel className="text-green-700 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">{t('inspections.export.excel')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">{t('inspections.export.excelDesc')}</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">{t('inspections.export.columnsToExport')}</h4>
              <div className="flex gap-2">
                <button onClick={selectAllColumns} className="text-xs text-blue-600 dark:text-blue-400 hover:underline">{t('inspections.export.selectAll')}</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">{t('inspections.export.resetToDefault')}</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-teal-100 dark:bg-teal-900/30 text-teal-800 dark:text-teal-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-teal-600 focus:ring-teal-500" />
                  <span className="text-sm truncate">{t(col.labelKey)}</span>
                </label>
              ))}
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">{t('inspections.export.columnsSelected', { count: selectedColumns.length })}</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' && t('inspections.export.exportingSelected', { count: selectedCount })}
            {scope === 'all_on_page' && t('inspections.export.exportingPage', { count: pageCount })}
            {scope === 'all_with_filters' && t('inspections.export.exportingAll', { count: totalCount })}
          </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}>{t('common.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-teal-600 hover:bg-teal-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>{t('inspections.export.exporting')}</>) : (<><FaDownload />{t('inspections.export.exportButton')}</>)}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// Status badge styles
const getStatusStyle = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'open': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
    case 'in progress': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300';
    case 'closed': return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
    case 'pending review': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
    default: return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
  }
};

// Workflow state badge styles
const getWorkflowStateStyle = (state: string) => {
  switch (state?.toLowerCase()) {
    case 'draft': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300';
    case 'sent to supervisor': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300';
    case 'closed': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300';
    default: return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
  }
};

// Inspection type badge styles
const getInspectionTypeStyle = (type: string) => {
  switch (type?.toLowerCase()) {
    case 'inspection': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
    case 'safety inspection': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300';
    default: return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
  }
};

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

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

  // ── Permission hook — same pattern as ModernDashboard ────────────────────
  // useUserPermissions('Issue Type') calls apiService.getPermissionFilters('Issue Type')
  // which hits the correct endpoint internally — no manual fetch needed.
  const [permittedIssueTypes, setPermittedIssueTypes] = useState<string[]>([]);
  const [isWoAdmin, setIsWoAdmin] = useState(true);

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

  const setCurrentPage = useCallback((pageOrUpdater: number | ((p: number) => number)) => {
    const next = typeof pageOrUpdater === 'function' ? pageOrUpdater(currentPage) : pageOrUpdater;
    setSearchParams((prev) => {
      const nextParams = new URLSearchParams(prev);
      nextParams.set('page', String(next));
      return nextParams;
    });
  }, [currentPage, setSearchParams]);

  const EXPORT_COLUMNS = [
    { key: 'name', labelKey: 'inspections.export.inspectionId', default: true },
    { key: 'inspection_type', labelKey: 'inspections.export.inspectionType', default: true },
    { key: 'status', labelKey: 'inspections.export.status', default: true },
    { key: 'workflow_state', labelKey: 'inspections.export.workflowState', default: true },
    { key: 'inspection_date', labelKey: 'inspections.export.inspectionDate', default: true },
    { key: 'target_closure_date', labelKey: 'inspections.export.targetClosureDate', default: true },
    { key: 'requested_by', labelKey: 'inspections.export.requestedBy', default: true },
    { key: 'work_order_type', labelKey: 'inspections.export.technicalDepartment', default: false },
    { key: 'extension_no', labelKey: 'inspections.export.extensionNo', default: false },
    { key: 'department', labelKey: 'inspections.export.department', default: false },
    { key: 'location', labelKey: 'inspections.export.location', default: false },
    { key: 'assigned_technician', labelKey: 'inspections.export.assignedTechnician', default: false },
    { key: 'linked_corrective_wo_no', labelKey: 'inspections.export.linkedWorkOrder', default: true },
    { key: 'observation_note', labelKey: 'inspections.export.observationNote', default: false },
    { key: 'technical_response', labelKey: 'inspections.export.technicalResponse', default: false },
    { key: 'creation', labelKey: 'inspections.export.createdOn', default: false },
    { key: 'modified', labelKey: 'inspections.export.modifiedOn', default: false },
    { key: 'owner', labelKey: 'inspections.export.createdBy', default: false },
  ];

  const [pageSize] = useState(20);
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());
  const [showExportModal, setShowExportModal] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [showReportModal, setShowReportModal] = useState(false);

  // ✅ Roles allowed to delete inspections and add new inspections
  const INSPECTION_ALLOWED_ROLES = [
    'System Manager',
    'Contractor Supervisor', 
    'Contractor Manager',
    'Work Control'
  ];

  // ✅ State for role-based permissions
  const [canDelete, setCanDelete] = useState(false);
  const [canAddInspection, setCanAddInspection] = useState(false);
  const [userRoles, setUserRoles] = useState<string[]>([]);
  const [listIsSystemManager, setListIsSystemManager] = useState(false);

  // ✅ Check user permissions based on roles
  useEffect(() => {
    const checkPermissions = async () => {
      try {
        const response = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ roles: INSPECTION_ALLOWED_ROLES.join(',') })
        });
        const data = await response.json();
        if (data.message) {
          const hasPermission = data.message.has_role;
          setCanDelete(hasPermission);
          setCanAddInspection(hasPermission);
        }

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

        // Fetch Issue Type permissions via Work_Order mapping (confirmed working endpoint)
        try {
          const permRes = await fetch(
            '/api/method/asset_lite.api.userperm_api.get_permission_filters?target_doctype=Work_Order',
            { credentials: 'include' }
          );
          const permData = await permRes.json();
          const msg = permData.message || {};
          setIsWoAdmin(msg.is_admin ?? true);
          setPermittedIssueTypes(msg.restrictions?.['Issue Type']?.values || []);
        } catch (e) {
          console.error('Error fetching issue type permissions:', e);
          setIsWoAdmin(true);
          setPermittedIssueTypes([]);
        }
      } catch (error) {
        console.error('Error checking permissions:', error);
        setCanDelete(false);
        setCanAddInspection(false);
      }
    };

    checkPermissions();
  }, []);

  // Filters
  const [dateFilterBy, setDateFilterBy] = useState<'' | 'creation' | 'modified'>(() => (searchParams.get('date_filter_by') as '' | 'creation' | 'modified') || '');
  const [dateStart, setDateStart] = useState<string>(() => searchParams.get('date_start') || '');
  const [dateEnd, setDateEnd] = useState<string>(() => searchParams.get('date_end') || '');
  const [statusFilter, setStatusFilter] = useState<string>(() => searchParams.get('status') || '');
  const [workflowStateFilter, setWorkflowStateFilter] = useState<string>(() => searchParams.get('workflow_state') || '');
  const [inspectionTypeFilter, setInspectionTypeFilter] = useState<string>(() => searchParams.get('inspection_type') || '');
  const [workOrderFilter, setWorkOrderFilter] = useState<string>(() => searchParams.get('work_order') || '');
  const [departmentFilter, setDepartmentFilter] = useState<string>(() => searchParams.get('department') || '');

  const [sortBy, setSortBy] = useState<string>(() => searchParams.get('sort_by') || 'creation desc');
  const [isFilterExpanded, setIsFilterExpanded] = useState(false);
  const [activeFilterCount, setActiveFilterCount] = useState(0);
  const [savedFilters, setSavedFilters] = useState<any[]>([]);
  const [showSaveFilterModal, setShowSaveFilterModal] = useState(false);
  const [filterPresetName, setFilterPresetName] = useState('');

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

  const hasDateFilter = dateFilterBy && (dateStart || dateEnd);
  useEffect(() => {
    const count = [statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter].filter(Boolean).length + (hasDateFilter ? 1 : 0);
    setActiveFilterCount(count);
  }, [statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter, hasDateFilter]);

  const apiFilters = useMemo(() => {
    const filters: Record<string, any> = {};
    if (statusFilter) filters['status'] = statusFilter;
    if (workflowStateFilter) filters['workflow_state'] = workflowStateFilter;
    if (inspectionTypeFilter) filters['inspection_type'] = inspectionTypeFilter;
    if (workOrderFilter) filters['linked_corrective_wo_no'] = workOrderFilter;
    if (departmentFilter) filters['work_order_type'] = departmentFilter;
    Object.assign(filters, buildDateRangeFilters(dateFilterBy, dateStart, dateEnd));
    filters['custom_delete_status'] = ['!=', 'Deleted'];
    return filters;
  }, [statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter, dateFilterBy, dateStart, dateEnd]);

  const orderBy = ['creation desc', 'creation asc', 'modified desc', 'modified asc', 'name asc', 'name desc'].includes(sortBy) ? sortBy : 'creation desc';
  const { inspections, loading, error, totalCount, refetch } = useInspectionList({
    filters: apiFilters,
    limit_start: (currentPage - 1) * pageSize,
    limit_page_length: pageSize,
    order_by: orderBy,
  });

  useEffect(() => { if (!loading && !initialLoadComplete) setInitialLoadComplete(true); }, [loading, initialLoadComplete]);

  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 (statusFilter) next.set('status', statusFilter); else next.delete('status');
      if (workflowStateFilter) next.set('workflow_state', workflowStateFilter); else next.delete('workflow_state');
      if (inspectionTypeFilter) next.set('inspection_type', inspectionTypeFilter); else next.delete('inspection_type');
      if (workOrderFilter) next.set('work_order', workOrderFilter); else next.delete('work_order');
      if (departmentFilter) next.set('department', departmentFilter); else next.delete('department');
      if (sortBy && sortBy !== 'creation desc') next.set('sort_by', sortBy); else next.delete('sort_by');
      next.set('page', '1');
      return next;
    });
  }, [dateFilterBy, dateStart, dateEnd, statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter, sortBy]);

  useEffect(() => { setSelectedRows(new Set()); }, [dateFilterBy, dateStart, dateEnd, statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter, currentPage]);

  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 totalPages = Math.ceil(totalCount / pageSize);
  const formatDate = (dateStr: string) => dateStr ? new Date(dateStr).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '-';

  const clearFilters = () => {
    setDateFilterBy(''); setDateStart(''); setDateEnd('');
    setSortBy('creation desc');
    setStatusFilter(''); setWorkflowStateFilter(''); setInspectionTypeFilter(''); setWorkOrderFilter(''); setDepartmentFilter('');
    setSearchParamsRef.current((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('status'); next.delete('workflow_state'); next.delete('inspection_type'); next.delete('work_order'); next.delete('department');
      next.set('page', '1');
      return next;
    });
  };
  const hasActiveFilters = hasDateFilter || !!statusFilter || !!workflowStateFilter || !!inspectionTypeFilter || !!workOrderFilter || !!departmentFilter;

  const handleSaveFilterPreset = () => {
    if (!filterPresetName.trim()) { alert(t('common.enterFilterName')); return; }
    const preset = { id: Date.now(), name: filterPresetName, filters: { dateFilterBy, dateStart, dateEnd, sortBy, statusFilter, workflowStateFilter, inspectionTypeFilter, workOrderFilter, departmentFilter } };
    const updated = [...savedFilters, preset];
    setSavedFilters(updated);
    setFilterPresetName('');
    setShowSaveFilterModal(false);
    localStorage.setItem('inspectionFilterPresets', JSON.stringify(updated));
  };

  const handleLoadFilterPreset = (preset: any) => {
    const f = preset.filters;
    setDateFilterBy(f.dateFilterBy || ''); setDateStart(f.dateStart || ''); setDateEnd(f.dateEnd || '');
    setSortBy(f.sortBy || 'creation desc');
    setStatusFilter(f.statusFilter || '');
    setWorkflowStateFilter(f.workflowStateFilter || '');
    setInspectionTypeFilter(f.inspectionTypeFilter || '');
    setWorkOrderFilter(f.workOrderFilter || '');
    setDepartmentFilter(f.departmentFilter || '');
  };

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

  const handleSelectRow = (name: string) => {
    setSelectedRows(prev => { const newSet = new Set(prev); newSet.has(name) ? newSet.delete(name) : newSet.add(name); return newSet; });
  };

  const handleSelectAll = () => { selectedRows.size === inspections.length ? setSelectedRows(new Set()) : setSelectedRows(new Set(inspections.map(i => i.name))); };
  const isAllSelected = inspections.length > 0 && selectedRows.size === inspections.length;
  const isSomeSelected = selectedRows.size > 0 && selectedRows.size < inspections.length;

  const fetchAllInspectionsForExport = useCallback(async (): Promise<any[]> => {
    const allInspections: any[] = [];
    let currentPageNum = 0;
    const pageSizeNum = 100;
    let hasMoreData = true;
    const filterArrays = toFrappeFilterArray(apiFilters);
    while (hasMoreData) {
      try {
        const response = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ doctype: 'Inspection', filters: filterArrays.length > 0 ? filterArrays : {}, fields: ['*'], limit_start: currentPageNum * pageSizeNum, limit_page_length: pageSizeNum, order_by: orderBy })
        });
        const data = await response.json();
        const results = data.message || [];
        allInspections.push(...results);
        if (results.length < pageSizeNum) hasMoreData = false; else currentPageNum++;
        if (currentPageNum > 100) { console.warn('Export safety limit reached'); hasMoreData = false; }
      } catch (error) { console.error('Error fetching inspections for export:', error); throw error; }
    }
    return allInspections;
  }, [apiFilters, orderBy]);

  const handleExport = async (scope: ExportScope, format: ExportFormat, columns: string[]) => {
    setIsExporting(true);
    try {
      let dataToExport: any[] = [];
      switch (scope) {
        case 'selected': dataToExport = inspections.filter(i => selectedRows.has(i.name)); break;
        case 'all_on_page': dataToExport = inspections; break;
        case 'all_with_filters': dataToExport = await fetchAllInspectionsForExport(); break;
      }
      if (dataToExport.length === 0) { alert(t('assets.noDataToExport')); return; }
      const columnLabels = columns.map(key => t(EXPORT_COLUMNS.find(c => c.key === key)?.labelKey || key));

      if (format === 'csv') {
        const csvContent = [columnLabels.join(','), ...dataToExport.map(item => columns.map(key => { let value = item[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 = `inspections_export_${new Date().toISOString().split('T')[0]}.csv`; link.click();
        URL.revokeObjectURL(url);
      } else if (format === 'excel') {
        const worksheetData = [columnLabels, ...dataToExport.map(item => columns.map(key => item[key] || ''))];
        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Inspections');
        XLSX.writeFile(workbook, `inspections_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 handleDelete = async (name: string) => {
    try {
      const response = await fetch(`/api/resource/Inspection/${name}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } });
      if (!response.ok) throw new Error('Failed to delete');
      setDeleteConfirmOpen(null); refetch(); alert(t('inspections.deletedSuccessfully'));
    } catch (err) { alert(`Failed to delete: ${err instanceof Error ? err.message : 'Unknown error'}`); }
  };

  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-teal-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">{t('inspections.loadingInspections')}</p>
        </div>
      </div>
    );
  }

  if (error) {
    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">{t('inspections.errorLoadingInspections')}</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button onClick={refetch} className="bg-teal-600 hover:bg-teal-700 text-white px-4 py-2 rounded">{t('common.tryAgain')}</button>
        </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>
          <div className="flex items-center gap-3">
            <FaClipboardCheck className="text-3xl text-teal-600 dark:text-teal-400" />
            <div>
              <h1 className="text-2xl font-bold text-gray-800 dark:text-white">{t('inspections.title')}</h1>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('common.total')}: {totalCount}
                {selectedRows.size > 0 && <span className="ml-2 text-teal-600 dark:text-teal-400">• {selectedRows.size} selected</span>}
                {loading && initialLoadComplete && <span className="ml-2 inline-flex items-center gap-1 text-xs text-teal-600 dark:text-teal-400"><div className="animate-spin rounded-full h-3 w-3 border-b-2 border-teal-500"></div>Updating...</span>}
              </p>
            </div>
          </div>
        </div>
        <div className="flex gap-3">
          <button onClick={() => setIsFilterExpanded(!isFilterExpanded)} className={`px-4 py-2 rounded-lg flex items-center gap-2 transition-colors ${isFilterExpanded || hasActiveFilters ? 'bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-300' : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'}`}>
            <FaFilter />{t('listPages.filters')}
            {activeFilterCount > 0 && <span className="bg-teal-600 text-white text-xs px-1.5 py-0.5 rounded-full">{activeFilterCount}</span>}
          </button>
          <button onClick={refetch} disabled={loading} className="px-4 py-2 rounded-lg bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 flex items-center gap-2 disabled:opacity-50">
            <FaSync className={loading ? 'animate-spin' : ''} />{t('listPages.refresh')}
          </button>
          {/* Inspection Report Button */}
          <button
            onClick={() => setShowReportModal(true)}
            className="bg-cyan-600 hover:bg-cyan-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all"
          >
            <FaClipboardCheck />
            <span className="font-medium">{t('inspections.inspectionReport')}</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('common.export')}</span>
            {selectedRows.size > 0 && <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">{selectedRows.size}</span>}
          </button>
          {canAddInspection && (
            <button onClick={() => navigate('/inspections/new')} className="bg-teal-600 hover:bg-teal-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('inspections.newInspection')}</span>
            </button>
          )}
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div><p className="text-sm text-gray-500 dark:text-gray-400">{t('common.total')}</p><p className="text-2xl font-bold text-gray-800 dark:text-white">{totalCount}</p></div>
            <FaClipboardCheck className="text-3xl text-teal-500" />
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div><p className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.stats.draft')}</p><p className="text-2xl font-bold text-orange-600">{inspections.filter(i => i.workflow_state === 'Draft').length}</p></div>
            <div className="w-10 h-10 rounded-full bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center"><span className="text-orange-600 font-bold">D</span></div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div><p className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.stats.pendingApproval')}</p><p className="text-2xl font-bold text-purple-600">{inspections.filter(i => i.workflow_state === 'Sent to Supervisor').length}</p></div>
            <div className="w-10 h-10 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center"><span className="text-purple-600 font-bold">P</span></div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div><p className="text-sm text-gray-500 dark:text-gray-400">{t('inspections.stats.closed')}</p><p className="text-2xl font-bold text-green-600">{inspections.filter(i => i.workflow_state === 'Closed').length}</p></div>
            <div className="w-10 h-10 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center"><span className="text-green-600 font-bold">C</span></div>
          </div>
        </div>
      </div>

      {/* Expandable Filter Panel */}
      {isFilterExpanded && (
        <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-teal-500 to-teal-600 dark:from-teal-600 dark:to-teal-700 px-4 py-3 rounded-t-lg">
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-3">
                <FaFilter className="text-white" size={16} /><h3 className="text-white font-semibold text-sm">{t('listPages.filters')}</h3>
                {activeFilterCount > 0 && <span className="bg-white text-teal-600 px-2 py-0.5 rounded-full text-xs font-bold">{activeFilterCount}</span>}
              </div>
              {hasActiveFilters && (
                <div className="flex-1 overflow-x-auto scrollbar-hide mx-2">
                  <div className="flex items-center gap-2 py-1">
                    {statusFilter && <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">{t('inspections.filterStatus')}:</span> {t(`inspections.status.${(statusFilter || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: statusFilter })}<button onClick={() => setStatusFilter('')} className="hover:text-red-500"><FaTimes className="text-[9px]" /></button></span>}
                    {workflowStateFilter && <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">{t('inspections.filterWorkflow')}:</span> {t(`inspections.workflowState.${(workflowStateFilter || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: workflowStateFilter })}<button onClick={() => setWorkflowStateFilter('')} className="hover:text-red-500"><FaTimes className="text-[9px]" /></button></span>}
                    {inspectionTypeFilter && <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">{t('inspections.filterType')}:</span> {t(`inspections.typeMap.${(inspectionTypeFilter || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: inspectionTypeFilter })}<button onClick={() => setInspectionTypeFilter('')} className="hover:text-red-500"><FaTimes className="text-[9px]" /></button></span>}
                    {workOrderFilter && <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">{t('inspections.filterWorkOrder')}:</span> {workOrderFilter}<button onClick={() => setWorkOrderFilter('')} className="hover:text-red-500"><FaTimes className="text-[9px]" /></button></span>}
                    {departmentFilter && <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">{t('inspections.filterDepartment')}:</span> {departmentFilter}<button onClick={() => setDepartmentFilter('')} className="hover:text-red-500"><FaTimes className="text-[9px]" /></button></span>}
                    {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={() => { setDateFilterBy(''); setDateStart(''); setDateEnd(''); }} className="hover:text-red-500"><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-teal-600 hover:bg-teal-50 rounded-md text-xs font-medium transition-all flex items-center gap-1.5"><FaSave size={12} /><span className="hidden sm:inline">{t('common.save')}</span></button>}
                {hasActiveFilters && <button onClick={clearFilters} 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">{t('common.clearFilters')}</span></button>}
              </div>
            </div>
          </div>
          <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} />{t('inspections.savedFilters')}</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-teal-100 to-blue-100 dark:from-teal-900/30 dark:to-blue-900/30 border border-teal-200 dark:border-teal-700 rounded-lg hover:shadow-md transition-all">
                      <button onClick={() => handleLoadFilterPreset(preset)} className="text-xs font-medium text-teal-700 dark:text-teal-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="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); setCurrentPage(1); }} 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-teal-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 range */}
                <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); setCurrentPage(1); }} 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-teal-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); setCurrentPage(1); }} 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-teal-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); setCurrentPage(1); }} 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-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white" />
                    </div>
                  </>
                )}
                {/* Status Filter */}
                <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={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setCurrentPage(1); }} 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-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="">{t('filters.allStatuses')}</option>
                    <option value="Open">{t('inspections.status.open')}</option>
                    <option value="In Progress">{t('inspections.status.in_progress')}</option>
                    <option value="Pending Review">{t('inspections.status.pending_review')}</option>
                    <option value="Closed">{t('inspections.status.closed')}</option>
                  </select>
                </div>
                {/* Workflow State Filter */}
                <div className="relative">
                  <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.workflowState')}</label>
                  <select value={workflowStateFilter} onChange={(e) => { setWorkflowStateFilter(e.target.value); setCurrentPage(1); }} 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-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="">{t('filters.allStates')}</option>
                    <option value="Draft">{t('inspections.workflowState.draft')}</option>
                    <option value="Sent to Work Control">{t('inspections.workflowState.sent_to_work_control')}</option>
                    <option value="Sent to technician">{t('inspections.workflowState.sent_to_technician')}</option>
                    <option value="Sent to Supervisor">{t('inspections.workflowState.sent_to_supervisor')}</option>
                    <option value="Closed">{t('inspections.workflowState.closed')}</option>
                  </select>
                </div>
                {/* Inspection Type Filter */}
                <div className="relative">
                  <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('inspections.type')}</label>
                  <select value={inspectionTypeFilter} onChange={(e) => { setInspectionTypeFilter(e.target.value); setCurrentPage(1); }} 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-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="">{t('filters.allTypes')}</option>
                    <option value="Inspection">{t('inspections.typeMap.inspection')}</option>
                    <option value="Safety Inspection">{t('inspections.typeMap.safety_inspection')}</option>
                  </select>
                </div>
                {/* Work Order Filter */}
                <div className="relative z-[60]">
                  <LinkField label={t('inspections.filterWorkOrder')}
                    doctype="Work_Order" value={workOrderFilter} onChange={(val) => { setWorkOrderFilter(val); setCurrentPage(1); }}
                    placeholder={t('inspections.selectWorkOrder')} disabled={false}
                    compact={true}
                    filters={{ custom_delete_status: ['!=', 'Deleted'] }}
                  />
                  {workOrderFilter && <button onClick={() => setWorkOrderFilter('')} className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"><FaTimes size={10} /></button>}
                </div>
                {/* Department Filter */}
                <div className="relative z-[59]">
                  <LinkField label={t('inspections.technicalDepartment')} doctype="Issue Type" value={departmentFilter} onChange={(val) => { setDepartmentFilter(val); setCurrentPage(1); }} placeholder={t('inspections.selectDepartment')} disabled={false} compact={true} />
                  {departmentFilter && <button onClick={() => setDepartmentFilter('')} className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"><FaTimes size={10} /></button>}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Save Filter Modal */}
      {showSaveFilterModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 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">{t('common.saveFilterPreset')}</h3>
            <input type="text" value={filterPresetName} onChange={(e) => setFilterPresetName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleSaveFilterPreset(); } }} placeholder={t('common.enterFilterName')} 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-teal-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">{t('common.cancel')}</button>
              <button onClick={handleSaveFilterPreset} className="px-4 py-2 text-sm font-medium text-white bg-teal-600 hover:bg-teal-700 rounded-md transition-colors flex items-center gap-2"><FaSave size={12} />{t('common.saveFilter')}</button>
            </div>
          </div>
        </div>
      )}

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

      {/* Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 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-teal-500"></div><span className="text-sm text-gray-600 dark:text-gray-300">{t('common.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-teal-600 dark:hover:text-teal-400 transition-colors" title={isAllSelected ? t('common.deselectAllTitle') : t('common.selectAllTitle')}>
                    {isAllSelected ? <FaCheckSquare className="text-teal-600 dark:text-teal-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-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.inspectionId')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.type')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('filters.status')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.workflowStateHeader')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.targetDate')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.requestedBy')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('inspections.linkedWorkOrder')}</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{t('listPages.actions')}</th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {inspections.length === 0 ? (
                <tr><td colSpan={9} className="px-4 py-12 text-center text-gray-500 dark:text-gray-400">
                  <div className="flex flex-col items-center"><FaClipboardCheck className="text-4xl text-gray-300 dark:text-gray-600 mb-2" /><p>{t('inspections.noInspectionsFound')}</p>
                    {hasActiveFilters ? (
                      <button onClick={clearFilters} className="mt-4 text-teal-600 dark:text-teal-400 hover:underline">{t('common.clearFilters')}</button>
                    ) : canAddInspection ? (
                      <button onClick={() => navigate('/inspections/new')} className="mt-4 text-teal-600 dark:text-teal-400 hover:underline">{t('inspections.createFirstInspection')}</button>
                    ) : null}
                  </div>
                </td></tr>
              ) : inspections.map((inspection) => (
                <tr key={inspection.name} className={`hover:bg-gray-50 dark:hover:bg-gray-700/50 cursor-pointer transition-colors ${selectedRows.has(inspection.name) ? 'bg-teal-50 dark:bg-teal-900/20' : getDeleteStatusRowClass(inspection.custom_delete_status)}`} title={inspection.custom_delete_status ? `Delete Status: ${inspection.custom_delete_status}` : undefined} onClick={() => navigate(`/inspections/${inspection.name}`)}>
                  <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                    <button onClick={() => handleSelectRow(inspection.name)} className="text-gray-500 dark:text-gray-400 hover:text-teal-600 dark:hover:text-teal-400 transition-colors">
                      {selectedRows.has(inspection.name) ? <FaCheckSquare className="text-teal-600 dark:text-teal-400" size={18} /> : <FaSquare size={18} />}
                    </button>
                  </td>
                  <td className="px-4 py-3"><span className="text-sm font-medium text-teal-600 dark:text-teal-400">{inspection.name}</span></td>
                  <td className="px-4 py-3">{inspection.inspection_type ? <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getInspectionTypeStyle(inspection.inspection_type)}`}>{t(`inspections.typeMap.${(inspection.inspection_type || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: inspection.inspection_type })}</span> : <span className="text-gray-400">-</span>}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getStatusStyle(inspection.status)}`}>
                      {inspection.status ? t(`inspections.status.${(inspection.status || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: inspection.status }) : '-'}
                    </span>
                  </td>
                  <td className="px-4 py-3"><span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getWorkflowStateStyle(inspection.workflow_state)}`}>{inspection.workflow_state ? t(`inspections.workflowState.${(inspection.workflow_state || '').toLowerCase().replace(/\s+/g, '_')}`, { defaultValue: inspection.workflow_state }) : '-'}</span></td>
                  <td className="px-4 py-3"><span className="text-sm text-gray-600 dark:text-gray-300">{formatDate(inspection.target_closure_date || '')}</span></td>
                  <td className="px-4 py-3"><span className="text-sm text-gray-600 dark:text-gray-300 line-clamp-1">{inspection.requested_by || '-'}</span></td>
                  <td className="px-4 py-3" onClick={(e) => e.stopPropagation()}>
                    {inspection.linked_corrective_wo_no ? (
                      <button onClick={() => navigate(`/work-orders/${inspection.linked_corrective_wo_no}`)} className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1">
                        {inspection.linked_corrective_wo_no}
                        <FaExternalLinkAlt size={10} />
                      </button>
                    ) : <span className="text-gray-400">-</span>}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                      <button onClick={() => navigate(`/inspections/${inspection.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={t('inspections.viewDetails')}><FaEye /></button>
                      <button onClick={() => navigate(`/inspections/${inspection.name}?edit=true`)} 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={t('inspections.editInspection')}><FaEdit /></button>
                      <div onClick={(e) => e.stopPropagation()}>
                        <DeleteRequestButton
                          doctype="Inspection"
                          docname={inspection.name}
                          currentDeleteStatus={(inspection.custom_delete_status ?? null) as DeleteStatus}
                          userRoles={userRoles}
                          isSystemManager={listIsSystemManager}
                          triggerMode
                          redirectOnDelete="/inspections"
                          onStatusChange={() => refetch()}
                        />
                      </div>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <ListPagination
          currentPage={currentPage}
          totalCount={totalCount}
          pageSize={pageSize}
          itemLabel={t('pagination.inspections')}
          onPageChange={(p) => setCurrentPage(p)}
        />
      </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('inspections.deleteInspection')}</h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{t('inspections.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('inspections.inspectionId')}:</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">{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"><FaTrash />{t('common.delete')}</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Inspection Report Modal */}
      <InspectionReportModal
        isOpen={showReportModal}
        onClose={() => setShowReportModal(false)}
        permittedIssueTypes={permittedIssueTypes}
        isAdmin={isWoAdmin}
      />

      <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 InspectionList;