// import React, { useState, useEffect, useCallback } from 'react';
// import { useTranslation } from 'react-i18next';
// import * as XLSX from 'xlsx';
// import {
//   FaTimes,
//   FaFileExcel,
//   FaFileCsv,
//   FaFilePdf,
//   FaPrint,
//   FaSpinner,
//   FaFilter,
//   FaChevronDown,
//   FaChevronUp,
//   FaSearch,
//   FaSync,
//   FaExternalLinkAlt,
//   FaClipboardCheck,
//   FaArrowLeft,
//   FaExclamationTriangle
// } from 'react-icons/fa';

// interface ReportColumn {
//   label: string;
//   fieldname: string;
//   fieldtype: string;
//   options?: string;
//   width?: number;
// }

// interface InspectionReportModalProps {
//   isOpen: boolean;
//   onClose: () => void;
// }

// const InspectionReportModal: React.FC<InspectionReportModalProps> = ({ isOpen, onClose }) => {
//   const { t } = useTranslation();
  
//   // State
//   const [loading, setLoading] = useState(false);
//   const [error, setError] = useState<string | null>(null);
//   const [reportData, setReportData] = useState<any[]>([]);
//   const [columns, setColumns] = useState<ReportColumn[]>([]);
//   const [filtersExpanded, setFiltersExpanded] = useState(true);
  
//   // Filter states
//   const [filterStatus, setFilterStatus] = useState('');
//   const [filterOnlyLate, setFilterOnlyLate] = useState('');
  
//   // Export states
//   const [isExporting, setIsExporting] = useState(false);

//   // Report name constant
//   const REPORT_NAME = 'Inspection';

//   /**
//    * Fetch report data from Frappe API
//    */
//   const fetchReportData = useCallback(async () => {
//     setLoading(true);
//     setError(null);
    
//     try {
//       // Build filters object
//       const filters: Record<string, any> = {};
//       if (filterStatus) filters.status = filterStatus;
//       if (filterOnlyLate) filters.only_late = filterOnlyLate;
      
//       const response = await fetch('/api/method/frappe.desk.query_report.run', {
//         method: 'POST',
//         headers: {
//           'Content-Type': 'application/json',
//         },
//         credentials: 'include',
//         body: JSON.stringify({
//           report_name: REPORT_NAME,
//           filters: filters,
//           ignore_prepared_report: 1
//         }),
//       });
      
//       const result = await response.json();
      
//       if (result.exc) {
//         throw new Error(result.exc);
//       }
      
//       if (result.message) {
//         // Set columns from report
//         if (result.message.columns && result.message.columns.length > 0) {
//           setColumns(result.message.columns);
//         }
        
//         // Set data (exclude the TOTAL row for display, we'll show summary separately)
//         if (result.message.result) {
//           setReportData(result.message.result);
//         } else {
//           setReportData([]);
//         }
//       }
//     } catch (err) {
//       console.error('Error fetching report:', err);
//       setError(err instanceof Error ? err.message : 'Failed to fetch report data');
//       setReportData([]);
//     } finally {
//       setLoading(false);
//     }
//   }, [filterStatus, filterOnlyLate]);

//   // Fetch data when modal opens or filters change
//   useEffect(() => {
//     if (isOpen) {
//       fetchReportData();
//     }
//   }, [isOpen, fetchReportData]);

//   // Handle escape key to close
//   useEffect(() => {
//     const handleEscape = (e: KeyboardEvent) => {
//       if (e.key === 'Escape' && isOpen) {
//         onClose();
//       }
//     };
    
//     document.addEventListener('keydown', handleEscape);
//     return () => document.removeEventListener('keydown', handleEscape);
//   }, [isOpen, onClose]);

//   // Prevent body scroll when modal is open
//   useEffect(() => {
//     if (isOpen) {
//       document.body.style.overflow = 'hidden';
//     } else {
//       document.body.style.overflow = 'unset';
//     }
//     return () => {
//       document.body.style.overflow = 'unset';
//     };
//   }, [isOpen]);

//   /**
//    * Clear all filters
//    */
//   const handleClearFilters = () => {
//     setFilterStatus('');
//     setFilterOnlyLate('');
//   };

//   /**
//    * Get data rows (exclude TOTAL row)
//    */
//   const getDataRows = () => {
//     return reportData.filter(row => row.status !== 'TOTAL');
//   };

//   /**
//    * Get total row
//    */
//   const getTotalRow = () => {
//     return reportData.find(row => row.status === 'TOTAL');
//   };

//   /**
//    * Export to CSV
//    */
//   const handleExportCSV = () => {
//     const dataRows = getDataRows();
//     if (dataRows.length === 0) return;
//     setIsExporting(true);
    
//     try {
//       const headers = columns.map(col => col.label);
//       const csvContent = [
//         headers.join(','),
//         ...dataRows.map(row => 
//           columns.map(col => {
//             let value = row[col.fieldname] || '';
//             // Escape commas and quotes
//             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 = `inspection_report_${new Date().toISOString().split('T')[0]}.csv`;
//       link.click();
//       URL.revokeObjectURL(url);
//     } finally {
//       setIsExporting(false);
//     }
//   };

//   /**
//    * Export to Excel
//    */
//   const handleExportExcel = () => {
//     const dataRows = getDataRows();
//     if (dataRows.length === 0) return;
//     setIsExporting(true);
    
//     try {
//       const headers = columns.map(col => col.label);
//       const worksheetData = [
//         headers,
//         ...dataRows.map(row => columns.map(col => row[col.fieldname] || ''))
//       ];
      
//       const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
      
//       // Set column widths
//       const colWidths = columns.map(col => ({ wch: col.width ? Math.floor(col.width / 7) : 15 }));
//       worksheet['!cols'] = colWidths;
      
//       const workbook = XLSX.utils.book_new();
//       XLSX.utils.book_append_sheet(workbook, worksheet, 'Inspection Report');
      
//       XLSX.writeFile(workbook, `inspection_report_${new Date().toISOString().split('T')[0]}.xlsx`);
//     } finally {
//       setIsExporting(false);
//     }
//   };

//   /**
//    * Print report
//    */
//   const handlePrint = () => {
//     const dataRows = getDataRows();
//     const totalRow = getTotalRow();
    
//     const printWindow = window.open('', '_blank');
//     if (!printWindow) {
//       alert('Please allow popups for this site to print the report.');
//       return;
//     }
    
//     const tableHTML = `
//       <!DOCTYPE html>
//       <html>
//       <head>
//         <title>Inspection Report</title>
//         <style>
//           body { font-family: Arial, sans-serif; margin: 20px; }
//           h1 { text-align: center; color: #333; margin-bottom: 20px; }
//           .meta { text-align: center; color: #666; margin-bottom: 20px; font-size: 12px; }
//           .summary { display: flex; justify-content: center; gap: 30px; margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; }
//           .summary-item { text-align: center; }
//           .summary-label { font-size: 11px; color: #666; }
//           .summary-value { font-size: 20px; font-weight: bold; color: #333; }
//           .summary-value.late { color: #DC2626; }
//           table { width: 100%; border-collapse: collapse; font-size: 11px; }
//           th { background-color: #0D9488; color: white; padding: 10px 8px; text-align: left; font-weight: 600; }
//           td { padding: 8px; border-bottom: 1px solid #ddd; }
//           tr:nth-child(even) { background-color: #f9f9f9; }
//           tr:hover { background-color: #f5f5f5; }
//           .status-open { color: #2563EB; font-weight: 500; }
//           .status-closed { color: #059669; font-weight: 500; }
//           .status-inprogress { color: #D97706; font-weight: 500; }
//           .late-yes { color: #DC2626; font-weight: 600; }
//           .late-no { color: #059669; }
//           @media print {
//             body { margin: 0; }
//             table { page-break-inside: auto; }
//             tr { page-break-inside: avoid; page-break-after: auto; }
//           }
//         </style>
//       </head>
//       <body>
//         <h1>Inspection Report</h1>
//         <div class="meta">
//           Generated on: ${new Date().toLocaleString()} | Total Records: ${dataRows.length}
//           ${filterStatus ? ` | Status: ${filterStatus}` : ''}
//           ${filterOnlyLate === 'Yes' ? ' | Only Late Inspections' : ''}
//         </div>
//         ${totalRow ? `
//         <div class="summary">
//           <div class="summary-item">
//             <div class="summary-label">Total Inspections</div>
//             <div class="summary-value">${totalRow.inspection || 0}</div>
//           </div>
//           <div class="summary-item">
//             <div class="summary-label">WO Created</div>
//             <div class="summary-value">${totalRow.wo_created || 0}</div>
//           </div>
//           <div class="summary-item">
//             <div class="summary-label">Not Closed On Time</div>
//             <div class="summary-value late">${totalRow.not_closed_on_time || 0}</div>
//           </div>
//         </div>
//         ` : ''}
//         <table>
//           <thead>
//             <tr>
//               <th>#</th>
//               ${columns.map(col => `<th>${col.label}</th>`).join('')}
//             </tr>
//           </thead>
//           <tbody>
//             ${dataRows.map((row, index) => `
//               <tr>
//                 <td>${index + 1}</td>
//                 ${columns.map(col => {
//                   let value = row[col.fieldname] || '-';
//                   let className = '';
                  
//                   // Add status classes
//                   if (col.fieldname === 'status') {
//                     if (value.toLowerCase() === 'open') className = 'status-open';
//                     else if (value.toLowerCase() === 'closed') className = 'status-closed';
//                     else if (value.toLowerCase().includes('progress')) className = 'status-inprogress';
//                   }
                  
//                   // Add late classes
//                   if (col.fieldname === 'not_closed_on_time') {
//                     className = value === 'Yes' ? 'late-yes' : 'late-no';
//                   }
                  
//                   return `<td class="${className}">${value}</td>`;
//                 }).join('')}
//               </tr>
//             `).join('')}
//           </tbody>
//         </table>
//         <script>
//           window.onload = function() { window.print(); }
//         </script>
//       </body>
//       </html>
//     `;
    
//     printWindow.document.write(tableHTML);
//     printWindow.document.close();
//   };

//   /**
//    * Export to PDF (using browser print)
//    */
//   const handleExportPDF = () => {
//     handlePrint(); // Uses print dialog which can save as PDF
//   };

//   /**
//    * Open in ERPNext
//    */
//   const handleOpenInERPNext = () => {
//     const baseUrl = window.location.origin;
//     let url = `${baseUrl}/app/query-report/${encodeURIComponent(REPORT_NAME)}`;
    
//     // Add filters to URL
//     const params = new URLSearchParams();
//     if (filterStatus) params.append('status', filterStatus);
//     if (filterOnlyLate) params.append('only_late', filterOnlyLate);
    
//     if (params.toString()) {
//       url += `?${params.toString()}`;
//     }
    
//     window.open(url, '_blank');
//   };

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

//   /**
//    * Get late badge color
//    */
//   const getLateColor = (value: string) => {
//     return value === 'Yes' 
//       ? 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300'
//       : 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';
//   };

//   /**
//    * Format cell value based on fieldtype
//    */
//   const formatCellValue = (value: any, column: ReportColumn) => {
//     if (value === null || value === undefined || value === '') return '-';
    
//     switch (column.fieldtype) {
//       case 'Date':
//         return new Date(value).toLocaleDateString('en-US', {
//           year: 'numeric',
//           month: 'short',
//           day: 'numeric'
//         });
//       case 'Datetime':
//         return new Date(value).toLocaleString('en-US', {
//           year: 'numeric',
//           month: 'short',
//           day: 'numeric',
//           hour: '2-digit',
//           minute: '2-digit'
//         });
//       default:
//         return String(value);
//     }
//   };

//   if (!isOpen) return null;

//   const dataRows = getDataRows();
//   const totalRow = getTotalRow();

//   return (
//     <div className="fixed inset-0 z-[80] bg-gray-50 dark:bg-gray-900 flex flex-col">
//       {/* Header */}
//       <div className="bg-gradient-to-r from-teal-600 to-cyan-600 px-6 py-4 flex-shrink-0 shadow-lg">
//         <div className="flex items-center justify-between">
//           <div className="flex items-center gap-4">
//             {/* Back Button */}
//             <button
//               onClick={onClose}
//               className="p-2 text-white/80 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
//               title="Go Back"
//             >
//               <FaArrowLeft size={18} />
//             </button>
            
//             <div className="flex items-center gap-3">
//               <FaClipboardCheck className="text-white text-xl" />
//               <div>
//                 <h2 className="text-xl font-bold text-white">Inspection Report</h2>
//                 <p className="text-white/70 text-sm">
//                   {dataRows.length} record{dataRows.length !== 1 ? 's' : ''} found
//                 </p>
//               </div>
//             </div>
//           </div>
          
//           <div className="flex items-center gap-2">
//             {/* Open in ERPNext Button */}
//             {/* <button
//               onClick={handleOpenInERPNext}
//               className="px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-lg text-sm font-medium transition-all flex items-center gap-2"
//               title="Open in ERPNext"
//             >
//               <FaExternalLinkAlt size={12} />
//               <span>Open in ERPNext</span>
//             </button> */}
            
//             {/* Close Button */}
//             <button
//               onClick={onClose}
//               className="p-2 text-white/80 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
//               title="Close (Esc)"
//             >
//               <FaTimes size={20} />
//             </button>
//           </div>
//         </div>
//       </div>

//       {/* Summary Cards */}
//       {totalRow && !loading && (
//         <div className="bg-white dark:bg-gray-800 px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
//           <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
//             <div className="bg-teal-50 dark:bg-teal-900/20 rounded-lg p-4 border border-teal-200 dark:border-teal-800">
//               <p className="text-xs text-teal-600 dark:text-teal-400 font-medium">Total Inspections</p>
//               <p className="text-2xl font-bold text-teal-700 dark:text-teal-300">{totalRow.inspection || 0}</p>
//             </div>
//             <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
//               <p className="text-xs text-blue-600 dark:text-blue-400 font-medium">Work Orders Created</p>
//               <p className="text-2xl font-bold text-blue-700 dark:text-blue-300">{totalRow.wo_created || 0}</p>
//             </div>
//             <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-4 border border-red-200 dark:border-red-800">
//               <div className="flex items-center gap-2">
//                 <FaExclamationTriangle className="text-red-500" />
//                 <p className="text-xs text-red-600 dark:text-red-400 font-medium">Not Closed On Time</p>
//               </div>
//               <p className="text-2xl font-bold text-red-700 dark:text-red-300">{totalRow.not_closed_on_time || 0}</p>
//             </div>
//           </div>
//         </div>
//       )}

//       {/* Toolbar */}
//       <div className="bg-white dark:bg-gray-800 px-6 py-3 border-b border-gray-200 dark:border-gray-700 flex-shrink-0 shadow-sm">
//         <div className="flex items-center justify-between gap-4 flex-wrap">
//           {/* Filter Toggle */}
//           <button
//             onClick={() => setFiltersExpanded(!filtersExpanded)}
//             className="flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
//           >
//             <FaFilter size={12} />
//             Filters
//             {(filterStatus || filterOnlyLate) && (
//               <span className="bg-teal-100 dark:bg-teal-900/50 text-teal-600 dark:text-teal-400 px-2 py-0.5 rounded-full text-xs font-bold">
//                 {[filterStatus, filterOnlyLate].filter(Boolean).length}
//               </span>
//             )}
//             {filtersExpanded ? <FaChevronUp size={10} /> : <FaChevronDown size={10} />}
//           </button>

//           {/* Action Buttons */}
//           <div className="flex items-center gap-2">
//             {/* Refresh */}
//             <button
//               onClick={fetchReportData}
//               disabled={loading}
//               className="p-2.5 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50"
//               title="Refresh"
//             >
//               <FaSync className={loading ? 'animate-spin' : ''} size={14} />
//             </button>

//             {/* Export Buttons */}
//             <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden">
//               <button
//                 onClick={handleExportCSV}
//                 disabled={dataRows.length === 0 || isExporting}
//                 className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
//                 title="Export as CSV"
//               >
//                 <FaFileCsv className="text-green-600" size={14} />
//                 <span>CSV</span>
//               </button>
//               <div className="w-px h-6 bg-gray-300 dark:bg-gray-600"></div>
//               <button
//                 onClick={handleExportExcel}
//                 disabled={dataRows.length === 0 || isExporting}
//                 className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
//                 title="Export as Excel"
//               >
//                 <FaFileExcel className="text-green-700" size={14} />
//                 <span>Excel</span>
//               </button>
//               <div className="w-px h-6 bg-gray-300 dark:bg-gray-600"></div>
//               <button
//                 onClick={handleExportPDF}
//                 disabled={dataRows.length === 0}
//                 className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
//                 title="Export as PDF"
//               >
//                 <FaFilePdf className="text-red-600" size={14} />
//                 <span>PDF</span>
//               </button>
//               <div className="w-px h-6 bg-gray-300 dark:bg-gray-600"></div>
//               <button
//                 onClick={handlePrint}
//                 disabled={dataRows.length === 0}
//                 className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
//                 title="Print"
//               >
//                 <FaPrint className="text-purple-600" size={14} />
//                 <span>Print</span>
//               </button>
//             </div>
//           </div>
//         </div>

//         {/* Expandable Filters */}
//         {filtersExpanded && (
//           <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
//             <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
//               {/* Status Filter */}
//               <div>
//                 <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
//                   Status
//                 </label>
//                 <select
//                   value={filterStatus}
//                   onChange={(e) => setFilterStatus(e.target.value)}
//                   className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
//                 >
//                   <option value="">All Status</option>
//                   <option value="Open">Open</option>
//                   <option value="In Progress">In Progress</option>
//                   <option value="Closed">Closed</option>
//                 </select>
//               </div>

//               {/* Only Late Filter */}
//               <div>
//                 <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
//                   Show Only Late
//                 </label>
//                 <select
//                   value={filterOnlyLate}
//                   onChange={(e) => setFilterOnlyLate(e.target.value)}
//                   className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
//                 >
//                   <option value="">All Inspections</option>
//                   <option value="Yes">Only Late (Not Closed On Time)</option>
//                 </select>
//               </div>

//               {/* Spacer */}
//               <div></div>

//               {/* Clear Filters Button */}
//               <div className="flex items-end">
//                 <button
//                   onClick={handleClearFilters}
//                   disabled={!filterStatus && !filterOnlyLate}
//                   className="px-4 py-2 text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
//                 >
//                   <FaTimes size={12} />
//                   Clear Filters
//                 </button>
//               </div>
//             </div>
//           </div>
//         )}
//       </div>

//       {/* Content - Full height scrollable area */}
//       <div className="flex-1 overflow-auto p-6">
//         {/* Loading State */}
//         {loading && (
//           <div className="flex items-center justify-center py-20">
//             <div className="text-center">
//               <FaSpinner className="animate-spin text-teal-500 text-5xl mx-auto mb-4" />
//               <p className="text-gray-600 dark:text-gray-400 text-lg">Loading report data...</p>
//             </div>
//           </div>
//         )}

//         {/* Error State */}
//         {error && !loading && (
//           <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-8 text-center max-w-lg mx-auto">
//             <p className="text-red-600 dark:text-red-400 mb-4 text-lg">{error}</p>
//             <button
//               onClick={fetchReportData}
//               className="px-6 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
//             >
//               Try Again
//             </button>
//           </div>
//         )}

//         {/* Empty State */}
//         {!loading && !error && dataRows.length === 0 && (
//           <div className="text-center py-20">
//             <FaSearch className="text-gray-300 dark:text-gray-600 text-6xl mx-auto mb-4" />
//             <p className="text-gray-500 dark:text-gray-400 text-xl">No data found</p>
//             <p className="text-gray-400 dark:text-gray-500 text-sm mt-2">
//               Try adjusting your filters
//             </p>
//           </div>
//         )}

//         {/* Data Table */}
//         {!loading && !error && dataRows.length > 0 && (
//           <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
//             <div className="overflow-x-auto">
//               <table className="w-full">
//                 <thead className="bg-gray-100 dark:bg-gray-700 sticky top-0">
//                   <tr>
//                     <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider w-16">
//                       #
//                     </th>
//                     {columns.map((col, index) => (
//                       <th
//                         key={index}
//                         className="px-4 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap"
//                         style={{ minWidth: col.width || 120 }}
//                       >
//                         {col.label}
//                       </th>
//                     ))}
//                   </tr>
//                 </thead>
//                 <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
//                   {dataRows.map((row, rowIndex) => (
//                     <tr
//                       key={rowIndex}
//                       className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
//                     >
//                       <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 font-medium">
//                         {rowIndex + 1}
//                       </td>
//                       {columns.map((col, colIndex) => {
//                         const value = row[col.fieldname];
//                         const formattedValue = formatCellValue(value, col);
                        
//                         // Special rendering for status
//                         if (col.fieldname === 'status') {
//                           return (
//                             <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
//                               <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(value)}`}>
//                                 {formattedValue}
//                               </span>
//                             </td>
//                           );
//                         }
                        
//                         // Special rendering for wo_created
//                         if (col.fieldname === 'wo_created') {
//                           return (
//                             <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
//                               <span className={`px-3 py-1 rounded-full text-xs font-medium ${
//                                 value === 'Yes' 
//                                   ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300'
//                                   : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
//                               }`}>
//                                 {formattedValue}
//                               </span>
//                             </td>
//                           );
//                         }
                        
//                         // Special rendering for not_closed_on_time
//                         if (col.fieldname === 'not_closed_on_time') {
//                           return (
//                             <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
//                               <span className={`px-3 py-1 rounded-full text-xs font-medium ${getLateColor(value)}`}>
//                                 {formattedValue}
//                               </span>
//                             </td>
//                           );
//                         }
                        
//                         // Link to inspection
//                         if (col.fieldname === 'inspection') {
//                           return (
//                             <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
//                               <a
//                                 href={`/asm_app/inspections/${value}`}
//                                 target="_blank"
//                                 rel="noopener noreferrer"
//                                 className="text-teal-600 dark:text-teal-400 hover:underline font-medium text-sm"
//                               >
//                                 {formattedValue}
//                               </a>
//                             </td>
//                           );
//                         }
                        
//                         // Default rendering
//                         return (
//                           <td
//                             key={colIndex}
//                             className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300"
//                             title={typeof value === 'string' && value.length > 50 ? value : undefined}
//                           >
//                             <div className="max-w-xs truncate">
//                               {formattedValue}
//                             </div>
//                           </td>
//                         );
//                       })}
//                     </tr>
//                   ))}
//                 </tbody>
//               </table>
//             </div>
//           </div>
//         )}
//       </div>

//       {/* Footer */}
//       <div className="bg-white dark:bg-gray-800 px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex-shrink-0 shadow-inner">
//         <div className="flex items-center justify-between">
//           <p className="text-sm text-gray-600 dark:text-gray-400">
//             Showing {dataRows.length} record{dataRows.length !== 1 ? 's' : ''}
//             {(filterStatus || filterOnlyLate) && ' (filtered)'}
//           </p>
//           <button
//             onClick={onClose}
//             className="px-6 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium transition-colors"
//           >
//             Close
//           </button>
//         </div>
//       </div>
//     </div>
//   );
// };

// export default InspectionReportModal;



import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import * as XLSX from 'xlsx';
import {
  FaTimes,
  FaFileExcel,
  FaFileCsv,
  FaFilePdf,
  FaPrint,
  FaSpinner,
  FaFilter,
  FaChevronDown,
  FaChevronUp,
  FaSearch,
  FaSync,
  FaArrowLeft,
  FaClipboardCheck,
  FaExclamationTriangle,
} from 'react-icons/fa';

interface ReportColumn {
  label: string;
  fieldname: string;
  fieldtype: string;
  options?: string;
  width?: number;
}

interface InspectionReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  permittedIssueTypes?: string[];
  isAdmin?: boolean;
}

const InspectionReportModal: React.FC<InspectionReportModalProps> = ({
  isOpen,
  onClose,
  permittedIssueTypes = [],
  isAdmin = true,
}) => {
  const { t } = useTranslation();

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [reportData, setReportData] = useState<any[]>([]);
  const [columns, setColumns] = useState<ReportColumn[]>([]);
  const [filtersExpanded, setFiltersExpanded] = useState(true);
  const [isExporting, setIsExporting] = useState(false);
  const [allIssueTypes, setAllIssueTypes] = useState<string[]>([]);

  const [filterStatus, setFilterStatus] = useState('');
  const [filterOnlyLate, setFilterOnlyLate] = useState('');
  const [filterWorkOrderType, setFilterWorkOrderType] = useState('');

  const REPORT_NAME = 'Inspection';

  // ── Fetch all issue types for admin dropdown ──────────────────────────────
  useEffect(() => {
    if (!isAdmin) return;
    const fetchIssueTypes = async () => {
      try {
        const r = await fetch(
          '/api/resource/Issue Type?fields=["name"]&limit_page_length=0&order_by=name asc',
          { headers: { Accept: 'application/json' }, credentials: 'include' }
        );
        const d = await r.json();
        if (d.data) setAllIssueTypes(d.data.map((x: any) => x.name));
      } catch (e) { console.error(e); }
    };
    fetchIssueTypes();
  }, [isAdmin]);

  // ── Auto-set department filter based on permissions ───────────────────────
  // Non-admin with 1 type → auto-lock
  // Non-admin with 2+ types → show dropdown, no auto-select
  // Admin → full dropdown, no auto-select
  useEffect(() => {
    if (!isAdmin && permittedIssueTypes.length === 1) {
      setFilterWorkOrderType(permittedIssueTypes[0]);
    } else {
      setFilterWorkOrderType('');
    }
  }, [permittedIssueTypes, isAdmin]);

  // ── Fetch report data ─────────────────────────────────────────────────────
  // CRITICAL: Never send a plain array to frappe.desk.query_report.run
  // Frappe's validate_filters_permissions crashes on array filter values.
  // Safe strategy:
  //   single string  → send as filter value (safe)
  //   multiple types → DO NOT send filter; filter client-side after fetch
  const fetchReportData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const filters: Record<string, any> = {};

      if (filterStatus) filters.status = filterStatus;
      if (filterOnlyLate) filters.only_late = filterOnlyLate;

      if (filterWorkOrderType) {
        filters.work_order_type = filterWorkOrderType;
      } else if (!isAdmin && permittedIssueTypes.length === 1) {
        filters.work_order_type = permittedIssueTypes[0];
      }
      // Multiple permitted types → not sent to API, filtered client-side below

      const response = await fetch('/api/method/frappe.desk.query_report.run', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          report_name: REPORT_NAME,
          filters,
          ignore_prepared_report: 1,
        }),
      });

      const result = await response.json();
      if (result.exc) throw new Error(result.exc);

      if (result.message) {
        if (result.message.columns?.length > 0) setColumns(result.message.columns);

        if (result.message.result) {
          let rows = result.message.result;

          // Client-side restriction for users with multiple permitted types
          if (!isAdmin && permittedIssueTypes.length > 1 && !filterWorkOrderType) {
            rows = rows.filter((r: any) =>
              permittedIssueTypes.includes(r.work_order_type)
            );
          }

          setReportData(rows);
        } else {
          setReportData([]);
        }
      }
    } catch (err) {
      console.error('Error fetching report:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch report data');
      setReportData([]);
    } finally {
      setLoading(false);
    }
  }, [filterStatus, filterOnlyLate, filterWorkOrderType, isAdmin, permittedIssueTypes]);

  useEffect(() => {
    if (isOpen) fetchReportData();
  }, [isOpen, fetchReportData]);

  useEffect(() => {
    const h = (e: KeyboardEvent) => { if (e.key === 'Escape' && isOpen) onClose(); };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [isOpen, onClose]);

  useEffect(() => {
    document.body.style.overflow = isOpen ? 'hidden' : 'unset';
    return () => { document.body.style.overflow = 'unset'; };
  }, [isOpen]);

  // ── Helpers ───────────────────────────────────────────────────────────────
  const handleClearFilters = () => {
    setFilterStatus('');
    setFilterOnlyLate('');
    if (isAdmin || permittedIssueTypes.length !== 1) setFilterWorkOrderType('');
  };

  const getDataRows = () => reportData.filter(r => r.status !== 'TOTAL');
  const getTotalRow = () => reportData.find(r => r.status === 'TOTAL');

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

  const getLateColor = (v: string) =>
    v === 'Yes'
      ? 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300'
      : 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300';

  const formatCellValue = (value: any, col: ReportColumn) => {
    if (value === null || value === undefined || value === '') return '-';
    switch (col.fieldtype) {
      case 'Date': return new Date(value).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
      case 'Datetime': return new Date(value).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
      default: return String(value);
    }
  };

  // ── Export helpers ────────────────────────────────────────────────────────
  const handleExportCSV = () => {
    const rows = getDataRows();
    if (!rows.length) return;
    setIsExporting(true);
    try {
      const csv = [
        columns.map(c => c.label).join(','),
        ...rows.map(row => columns.map(c => {
          let v = row[c.fieldname] || '';
          if (typeof v === 'string' && (v.includes(',') || v.includes('"') || v.includes('\n')))
            v = `"${v.replace(/"/g, '""')}"`;
          return v;
        }).join(',')),
      ].join('\n');
      const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `inspection_report_${new Date().toISOString().split('T')[0]}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } finally { setIsExporting(false); }
  };

  const handleExportExcel = () => {
    const rows = getDataRows();
    if (!rows.length) return;
    setIsExporting(true);
    try {
      const ws = XLSX.utils.aoa_to_sheet([
        columns.map(c => c.label),
        ...rows.map(row => columns.map(c => row[c.fieldname] || '')),
      ]);
      ws['!cols'] = columns.map(c => ({ wch: c.width ? Math.floor(c.width / 7) : 15 }));
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Inspection Report');
      XLSX.writeFile(wb, `inspection_report_${new Date().toISOString().split('T')[0]}.xlsx`);
    } finally { setIsExporting(false); }
  };

  const handlePrint = () => {
    const rows = getDataRows();
    const total = getTotalRow();
    const pw = window.open('', '_blank');
    if (!pw) { alert('Please allow popups to print.'); return; }
    pw.document.write(`<!DOCTYPE html><html><head><title>Inspection Report</title>
    <style>
      body{font-family:Arial,sans-serif;margin:20px}
      h1{text-align:center;color:#333;margin-bottom:20px}
      .meta{text-align:center;color:#666;margin-bottom:20px;font-size:12px}
      .summary{display:flex;justify-content:center;gap:30px;margin-bottom:20px;padding:15px;background:#f8f9fa;border-radius:8px}
      .summary-item{text-align:center}.summary-label{font-size:11px;color:#666}
      .summary-value{font-size:20px;font-weight:bold;color:#333}.summary-value.late{color:#DC2626}
      table{width:100%;border-collapse:collapse;font-size:11px}
      th{background-color:#0D9488;color:white;padding:10px 8px;text-align:left;font-weight:600}
      td{padding:8px;border-bottom:1px solid #ddd}
      tr:nth-child(even){background:#f9f9f9}
      .status-open{color:#2563EB;font-weight:500}
      .status-closed{color:#059669;font-weight:500}
      .status-inprogress{color:#D97706;font-weight:500}
      .late-yes{color:#DC2626;font-weight:600}.late-no{color:#059669}
      @media print{body{margin:0}tr{page-break-inside:avoid}}
    </style></head><body>
    <h1>Inspection Report</h1>
    <div class="meta">
      Generated on: ${new Date().toLocaleString()} | Records: ${rows.length}
      ${filterStatus ? ` | Status: ${filterStatus}` : ''}
      ${filterWorkOrderType ? ` | Dept: ${filterWorkOrderType}` : ''}
      ${filterOnlyLate === 'Yes' ? ' | Only Late' : ''}
    </div>
    ${total ? `
    <div class="summary">
      <div class="summary-item"><div class="summary-label">Total Inspections</div><div class="summary-value">${total.inspection || 0}</div></div>
      <div class="summary-item"><div class="summary-label">WO Created</div><div class="summary-value">${total.wo_created || 0}</div></div>
      <div class="summary-item"><div class="summary-label">Not Closed On Time</div><div class="summary-value late">${total.not_closed_on_time || 0}</div></div>
    </div>` : ''}
    <table>
      <thead><tr><th>#</th>${columns.map(c => `<th>${c.label}</th>`).join('')}</tr></thead>
      <tbody>
        ${rows.map((row, i) => `
          <tr><td>${i + 1}</td>${columns.map(c => {
            let v = row[c.fieldname] || '-';
            let cls = '';
            if (c.fieldname === 'status') {
              if (String(v).toLowerCase() === 'open') cls = 'status-open';
              else if (String(v).toLowerCase() === 'closed') cls = 'status-closed';
              else if (String(v).toLowerCase().includes('progress')) cls = 'status-inprogress';
            }
            if (c.fieldname === 'not_closed_on_time') cls = v === 'Yes' ? 'late-yes' : 'late-no';
            return `<td class="${cls}">${v}</td>`;
          }).join('')}</tr>
        `).join('')}
      </tbody>
    </table>
    <script>window.onload=function(){window.print()}</script>
    </body></html>`);
    pw.document.close();
  };

  const handleExportPDF = () => handlePrint();

  // ── Render guard ──────────────────────────────────────────────────────────
  if (!isOpen) return null;

  const dataRows = getDataRows();
  const totalRow = getTotalRow();
  const hasActiveFilters = !!(filterStatus || filterOnlyLate || filterWorkOrderType);
  const activeFilterCount = [filterStatus, filterOnlyLate, filterWorkOrderType].filter(Boolean).length;
  const dropdownTypes = isAdmin ? allIssueTypes : permittedIssueTypes;
  const showDeptFilter = isAdmin || permittedIssueTypes.length >= 1;

  return (
    <div className="fixed inset-0 z-[80] bg-gray-50 dark:bg-gray-900 flex flex-col">

      {/* ── Header ── */}
      <div className="bg-gradient-to-r from-teal-600 to-cyan-600 px-6 py-4 flex-shrink-0 shadow-lg">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button
              onClick={onClose}
              className="p-2 text-white/80 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
              title="Go Back"
            >
              <FaArrowLeft size={18} />
            </button>
            <div className="flex items-center gap-3">
              <FaClipboardCheck className="text-white text-xl" />
              <div>
                <h2 className="text-xl font-bold text-white">Inspection Report</h2>
                <p className="text-white/70 text-sm">
                  {dataRows.length} record{dataRows.length !== 1 ? 's' : ''} found
                  {filterWorkOrderType && (
                    <span className="ml-2 bg-white/20 px-2 py-0.5 rounded-full text-xs">
                      {filterWorkOrderType}
                    </span>
                  )}
                </p>
              </div>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-white/80 hover:text-white hover:bg-white/20 rounded-lg transition-colors"
            title="Close (Esc)"
          >
            <FaTimes size={20} />
          </button>
        </div>
      </div>

      {/* ── Summary Cards ── */}
      {totalRow && !loading && (
        <div className="bg-white dark:bg-gray-800 px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-teal-50 dark:bg-teal-900/20 rounded-lg p-4 border border-teal-200 dark:border-teal-800">
              <p className="text-xs text-teal-600 dark:text-teal-400 font-medium">Total Inspections</p>
              <p className="text-2xl font-bold text-teal-700 dark:text-teal-300">{totalRow.inspection || 0}</p>
            </div>
            <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
              <p className="text-xs text-blue-600 dark:text-blue-400 font-medium">Work Orders Created</p>
              <p className="text-2xl font-bold text-blue-700 dark:text-blue-300">{totalRow.wo_created || 0}</p>
            </div>
            <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-4 border border-red-200 dark:border-red-800">
              <div className="flex items-center gap-2">
                <FaExclamationTriangle className="text-red-500" />
                <p className="text-xs text-red-600 dark:text-red-400 font-medium">Not Closed On Time</p>
              </div>
              <p className="text-2xl font-bold text-red-700 dark:text-red-300">{totalRow.not_closed_on_time || 0}</p>
            </div>
          </div>
        </div>
      )}

      {/* ── Toolbar ── */}
      <div className="bg-white dark:bg-gray-800 px-6 py-3 border-b border-gray-200 dark:border-gray-700 flex-shrink-0 shadow-sm">
        <div className="flex items-center justify-between gap-4 flex-wrap">

          <button
            onClick={() => setFiltersExpanded(!filtersExpanded)}
            className="flex items-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            <FaFilter size={12} />
            Filters
            {hasActiveFilters && (
              <span className="bg-teal-100 dark:bg-teal-900/50 text-teal-600 dark:text-teal-400 px-2 py-0.5 rounded-full text-xs font-bold">
                {activeFilterCount}
              </span>
            )}
            {filtersExpanded ? <FaChevronUp size={10} /> : <FaChevronDown size={10} />}
          </button>

          <div className="flex items-center gap-2">
            <button
              onClick={fetchReportData}
              disabled={loading}
              className="p-2.5 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50"
              title="Refresh"
            >
              <FaSync className={loading ? 'animate-spin' : ''} size={14} />
            </button>

            <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden">
              <button
                onClick={handleExportCSV}
                disabled={!dataRows.length || isExporting}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
                title="Export as CSV"
              >
                <FaFileCsv className="text-green-600" size={14} /><span>CSV</span>
              </button>
              <div className="w-px h-6 bg-gray-300 dark:bg-gray-600" />
              <button
                onClick={handleExportExcel}
                disabled={!dataRows.length || isExporting}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
                title="Export as Excel"
              >
                <FaFileExcel className="text-green-700" size={14} /><span>Excel</span>
              </button>
              <div className="w-px h-6 bg-gray-300 dark:bg-gray-600" />
              <button
                onClick={handleExportPDF}
                disabled={!dataRows.length}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
                title="Export as PDF"
              >
                <FaFilePdf className="text-red-600" size={14} /><span>PDF</span>
              </button>
              <div className="w-px h-6 bg-gray-300 dark:bg-gray-600" />
              <button
                onClick={handlePrint}
                disabled={!dataRows.length}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors flex items-center gap-2 disabled:opacity-50"
                title="Print"
              >
                <FaPrint className="text-purple-600" size={14} /><span>Print</span>
              </button>
            </div>
          </div>
        </div>

        {/* ── Filters panel ── */}
        {filtersExpanded && (
          <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">

              {/* Status */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Status
                </label>
                <select
                  value={filterStatus}
                  onChange={e => setFilterStatus(e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">All Status</option>
                  <option value="Open">Open</option>
                  <option value="In Progress">In Progress</option>
                  <option value="Closed">Closed</option>
                </select>
              </div>

              {/* Only Late */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Show Only Late
                </label>
                <select
                  value={filterOnlyLate}
                  onChange={e => setFilterOnlyLate(e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">All Inspections</option>
                  <option value="Yes">Only Late (Not Closed On Time)</option>
                </select>
              </div>

              {/* Technical Department */}
              {showDeptFilter && (
                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Technical Department
                  </label>

                  {/* Non-admin with exactly 1 permitted type → locked read-only */}
                  {!isAdmin && permittedIssueTypes.length === 1 ? (
                    <div className="w-full px-3 py-2 text-sm border border-gray-200 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-600 text-gray-700 dark:text-gray-300 flex items-center gap-2">
                      <span className="w-2 h-2 rounded-full bg-teal-400 flex-shrink-0" />
                      {filterWorkOrderType}
                      <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500 uppercase tracking-wide">
                        Restricted
                      </span>
                    </div>
                  ) : (
                    /* Admin or non-admin with multiple permitted types → dropdown */
                    <select
                      value={filterWorkOrderType}
                      onChange={e => setFilterWorkOrderType(e.target.value)}
                      className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    >
                      <option value="">{isAdmin ? 'All Departments' : 'Select Department'}</option>
                      {dropdownTypes.map(type => (
                        <option key={type} value={type}>{type}</option>
                      ))}
                    </select>
                  )}
                </div>
              )}

              {/* Clear filters */}
              <div className="flex items-end">
                <button
                  onClick={handleClearFilters}
                  disabled={!hasActiveFilters}
                  className="px-4 py-2 text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  <FaTimes size={12} />Clear Filters
                </button>
              </div>
            </div>

            {/* Active filter badges */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2 mt-3">
                {filterStatus && (
                  <span className="text-xs bg-teal-50 dark:bg-teal-900/30 text-teal-700 dark:text-teal-300 border border-teal-200 dark:border-teal-700 px-2 py-1 rounded-full">
                    Status: {filterStatus}
                  </span>
                )}
                {filterOnlyLate && (
                  <span className="text-xs bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-700 px-2 py-1 rounded-full">
                    Only Late
                  </span>
                )}
                {filterWorkOrderType && (
                  <span className="text-xs bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-700 px-2 py-1 rounded-full">
                    Dept: {filterWorkOrderType}
                  </span>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* ── Content ── */}
      <div className="flex-1 overflow-auto p-6">

        {loading && (
          <div className="flex items-center justify-center py-20">
            <div className="text-center">
              <FaSpinner className="animate-spin text-teal-500 text-5xl mx-auto mb-4" />
              <p className="text-gray-600 dark:text-gray-400 text-lg">Loading report data...</p>
            </div>
          </div>
        )}

        {error && !loading && (
          <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-8 text-center max-w-lg mx-auto">
            <p className="text-red-600 dark:text-red-400 mb-4 text-lg">{error}</p>
            <button
              onClick={fetchReportData}
              className="px-6 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
            >
              Try Again
            </button>
          </div>
        )}

        {!loading && !error && dataRows.length === 0 && (
          <div className="text-center py-20">
            <FaSearch className="text-gray-300 dark:text-gray-600 text-6xl mx-auto mb-4" />
            <p className="text-gray-500 dark:text-gray-400 text-xl">No data found</p>
            <p className="text-gray-400 dark:text-gray-500 text-sm mt-2">Try adjusting your filters</p>
          </div>
        )}

        {!loading && !error && dataRows.length > 0 && (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden shadow-sm">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-100 dark:bg-gray-700 sticky top-0">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider w-16">
                      #
                    </th>
                    {columns.map((col, i) => (
                      <th
                        key={i}
                        className="px-4 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap"
                        style={{ minWidth: col.width || 120 }}
                      >
                        {col.label}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {dataRows.map((row, ri) => (
                    <tr key={ri} className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
                      <td className="px-4 py-3 text-sm text-gray-500 dark:text-gray-400 font-medium">
                        {ri + 1}
                      </td>
                      {columns.map((col, ci) => {
                        const value = row[col.fieldname];
                        const fv = formatCellValue(value, col);

                        if (col.fieldname === 'status') return (
                          <td key={ci} className="px-4 py-3 whitespace-nowrap">
                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(value)}`}>
                              {fv}
                            </span>
                          </td>
                        );

                        if (col.fieldname === 'wo_created') return (
                          <td key={ci} className="px-4 py-3 whitespace-nowrap">
                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                              value === 'Yes'
                                ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300'
                                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                            }`}>
                              {fv}
                            </span>
                          </td>
                        );

                        if (col.fieldname === 'not_closed_on_time') return (
                          <td key={ci} className="px-4 py-3 whitespace-nowrap">
                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${getLateColor(value)}`}>
                              {fv}
                            </span>
                          </td>
                        );

                        if (col.fieldname === 'inspection') return (
                          <td key={ci} className="px-4 py-3 whitespace-nowrap">
                            <a
                              href={`/asm_app/inspections/${value}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-teal-600 dark:text-teal-400 hover:underline font-medium text-sm"
                            >
                              {fv}
                            </a>
                          </td>
                        );

                        return (
                          <td
                            key={ci}
                            className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300"
                            title={typeof value === 'string' && value.length > 50 ? value : undefined}
                          >
                            <div className="max-w-xs truncate">{fv}</div>
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* ── Footer ── */}
      <div className="bg-white dark:bg-gray-800 px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex-shrink-0 shadow-inner">
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Showing {dataRows.length} record{dataRows.length !== 1 ? 's' : ''}
            {hasActiveFilters && ' (filtered)'}
            {filterWorkOrderType && (
              <span className="ml-2 text-teal-600 dark:text-teal-400">· {filterWorkOrderType}</span>
            )}
          </p>
          <button
            onClick={onClose}
            className="px-6 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium transition-colors"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
};

export default InspectionReportModal;