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,
  FaHardHat,
  FaUsers,
  FaCheckCircle,
  FaClock,
  FaFolderOpen,
  FaArrowLeft
} from 'react-icons/fa';

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

// ── CHANGE 1: Added permittedIssueTypes and isAdmin to props interface ──
interface TechnicianWorkOrderSummaryReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  permittedIssueTypes?: string[];
  isAdmin?: boolean;
  defaultWorkOrderType?: string;
}

// ── CHANGE 2: Destructure new props with safe defaults ──
const TechnicianWorkOrderSummaryReportModal: React.FC<TechnicianWorkOrderSummaryReportModalProps> = ({
  isOpen,
  onClose,
  permittedIssueTypes = [],
  isAdmin = true,
  defaultWorkOrderType = ''
}) => {
  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(false);
  
  // Export states
  const [isExporting, setIsExporting] = useState(false);

  // All issue types for admin dropdown
const [allIssueTypes, setAllIssueTypes] = useState<string[]>([]);

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

  // ── CHANGE 3: Added filterWorkOrderType state ──
  const [filterWorkOrderType, setFilterWorkOrderType] = useState('');

  // ── CHANGE 4: Auto-apply permitted Issue Type or dashboard global filter ──
  useEffect(() => {
    if (!isAdmin && permittedIssueTypes.length === 1) {
      // Single permitted type — lock it in automatically
      setFilterWorkOrderType(permittedIssueTypes[0]);
    } else if (defaultWorkOrderType) {
      setFilterWorkOrderType(defaultWorkOrderType);
    } else {
      setFilterWorkOrderType('');
    }
  }, [permittedIssueTypes, isAdmin, defaultWorkOrderType]);

  // Report name constant
  const REPORT_NAME = 'Technician Work Order Summary';

  // ── CHANGE 5: fetchReportData now builds filters from permissions ──
  const fetchReportData = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      // Build filters based on user permissions
      const filters: Record<string, any> = {};

      // if (filterWorkOrderType) {
      //   // Explicit filter selected (or auto-locked for single-permitted users)
      //   filters.work_order_type = filterWorkOrderType;
     
      // } else if (!isAdmin && permittedIssueTypes.length > 0) {
      //   filters.work_order_type = permittedIssueTypes.length === 1
      //     ? permittedIssueTypes[0]
      //     : ['in', permittedIssueTypes];
      // }
      // isAdmin with no filterWorkOrderType → no filter = sees everything

      if (filterWorkOrderType) {
        filters.work_order_type = filterWorkOrderType;
      } else if (!isAdmin && permittedIssueTypes.length === 1) {
        filters.work_order_type = permittedIssueTypes[0];
      }
      // Multiple permitted types: no filter sent, client-side filtering 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 && result.message.columns.length > 0) {
          setColumns(result.message.columns);
        }
        // if (result.message.result) {
        //   setReportData(result.message.result);
        // } else {
        //   setReportData([]);
        // }
        if (result.message.result) {
          let rows = result.message.result;
          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);
    }
  // ── CHANGE 5 cont: Added filterWorkOrderType, isAdmin, permittedIssueTypes to deps ──
  }, [filterWorkOrderType, isAdmin, permittedIssueTypes]);

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

  /**
   * Calculate summary statistics
   */
  const getSummaryStats = () => {
    const totalTechnicians = reportData.length;
    const totalWorkOrders = reportData.reduce((sum, row) => sum + (parseInt(row.total) || 0), 0);
    const totalCompleted = reportData.reduce((sum, row) => sum + (parseInt(row.completed) || 0), 0);
    const totalInProgress = reportData.reduce((sum, row) => sum + (parseInt(row.in_progress) || 0), 0);
    const totalOpen = reportData.reduce((sum, row) => sum + (parseInt(row.open) || 0), 0);
    const completionRate = totalWorkOrders > 0 ? ((totalCompleted / totalWorkOrders) * 100).toFixed(1) : '0';
    return { totalTechnicians, totalWorkOrders, totalCompleted, totalInProgress, totalOpen, completionRate };
  };

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

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

  /**
   * Print report
   */
  const handlePrint = () => {
    const stats = getSummaryStats();
    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>Technician Work Order Summary 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: 20px; margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; flex-wrap: wrap; }
          .summary-item { text-align: center; min-width: 100px; }
          .summary-label { font-size: 11px; color: #666; }
          .summary-value { font-size: 20px; font-weight: bold; color: #333; }
          .summary-value.completed { color: #10B981; }
          .summary-value.in-progress { color: #3B82F6; }
          .summary-value.open { color: #F59E0B; }
          table { width: 100%; border-collapse: collapse; font-size: 12px; }
          th { background-color: #8B5CF6; color: white; padding: 10px 8px; text-align: left; font-weight: 600; }
          td { padding: 10px 8px; border-bottom: 1px solid #ddd; }
          tr:nth-child(even) { background-color: #f9f9f9; }
          tr:hover { background-color: #f5f5f5; }
          .count-cell { font-weight: 600; text-align: center; }
          .completed { color: #10B981; }
          .in-progress { color: #3B82F6; }
          .open { color: #F59E0B; }
          @media print {
            body { margin: 0; }
            table { page-break-inside: auto; }
            tr { page-break-inside: avoid; page-break-after: auto; }
          }
        </style>
      </head>
      <body>
        <h1>Technician Work Order Summary Report</h1>
        <div class="meta">
          Generated on: ${new Date().toLocaleString()}
          ${filterWorkOrderType ? ` | Department: ${filterWorkOrderType}` : ''}
        </div>
        <div class="summary">
          <div class="summary-item">
            <div class="summary-label">Total Technicians</div>
            <div class="summary-value">${stats.totalTechnicians}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">Total Work Orders</div>
            <div class="summary-value">${stats.totalWorkOrders}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">Completed</div>
            <div class="summary-value completed">${stats.totalCompleted}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">In Progress</div>
            <div class="summary-value in-progress">${stats.totalInProgress}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">Open</div>
            <div class="summary-value open">${stats.totalOpen}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">Completion Rate</div>
            <div class="summary-value completed">${stats.completionRate}%</div>
          </div>
        </div>
        <table>
          <thead>
            <tr>
              <th>#</th>
              ${columns.map(col => `<th>${col.label}</th>`).join('')}
            </tr>
          </thead>
          <tbody>
            ${reportData.map((row, index) => `
              <tr>
                <td>${index + 1}</td>
                ${columns.map(col => {
                  let value = row[col.fieldname] || '-';
                  let className = '';
                  if (col.fieldname === 'completed') className = 'count-cell completed';
                  else if (col.fieldname === 'in_progress') className = 'count-cell in-progress';
                  else if (col.fieldname === 'open') className = 'count-cell open';
                  else if (col.fieldname === 'total') className = 'count-cell';
                  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();
  };

  const handleExportPDF = () => {
    handlePrint();
  };

  const handleOpenInERPNext = () => {
    const baseUrl = window.location.origin;
    const url = `${baseUrl}/app/query-report/${encodeURIComponent(REPORT_NAME)}`;
    window.open(url, '_blank');
  };

  const formatCellValue = (value: any, column: ReportColumn) => {
    if (value === null || value === undefined || value === '') return '-';
    switch (column.fieldtype) {
      case 'Int':
        return parseInt(value) || 0;
      case 'Float':
        return typeof value === 'number' ? value.toFixed(2) : value;
      default:
        return String(value);
    }
  };

  if (!isOpen) return null;

  const stats = getSummaryStats();

  // ── CHANGE 6: Derived values for filter badge count ──
  const hasActiveFilters = !!filterWorkOrderType;

  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-purple-600 to-indigo-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">
              <FaHardHat className="text-white text-xl" />
              <div>
                <h2 className="text-xl font-bold text-white">Technician Work Order Summary</h2>
                <p className="text-white/70 text-sm">
                  {reportData.length} technician{reportData.length !== 1 ? 's' : ''} found
                  {/* ── CHANGE 6 cont: Show active department in header ── */}
                  {filterWorkOrderType && (
                    <span className="ml-2 bg-white/20 px-2 py-0.5 rounded-full text-xs">
                      {filterWorkOrderType}
                    </span>
                  )}
                </p>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <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 */}
      {!loading && reportData.length > 0 && (
        <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-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            <div className="bg-indigo-50 dark:bg-indigo-900/20 rounded-lg p-4 border border-indigo-200 dark:border-indigo-800">
              <div className="flex items-center gap-3">
                <FaUsers className="text-indigo-500 text-xl" />
                <div>
                  <p className="text-xs text-indigo-600 dark:text-indigo-400 font-medium">Technicians</p>
                  <p className="text-xl font-bold text-indigo-700 dark:text-indigo-300">{stats.totalTechnicians}</p>
                </div>
              </div>
            </div>
            {/* <div className="bg-purple-50 dark:bg-purple-900/20 rounded-lg p-4 border border-purple-200 dark:border-purple-800">
              <div className="flex items-center gap-3">
                <FaHardHat className="text-purple-500 text-xl" />
                <div>
                  <p className="text-xs text-purple-600 dark:text-purple-400 font-medium">Total Work Orders</p>
                  <p className="text-xl font-bold text-purple-700 dark:text-purple-300">{stats.totalWorkOrders}</p>
                </div>
              </div>
            </div>
            <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-4 border border-green-200 dark:border-green-800">
              <div className="flex items-center gap-3">
                <FaCheckCircle className="text-green-500 text-xl" />
                <div>
                  <p className="text-xs text-green-600 dark:text-green-400 font-medium">Completed</p>
                  <p className="text-xl font-bold text-green-700 dark:text-green-300">{stats.totalCompleted}</p>
                </div>
              </div>
            </div>
            <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
              <div className="flex items-center gap-3">
                <FaClock className="text-blue-500 text-xl" />
                <div>
                  <p className="text-xs text-blue-600 dark:text-blue-400 font-medium">In Progress</p>
                  <p className="text-xl font-bold text-blue-700 dark:text-blue-300">{stats.totalInProgress}</p>
                </div>
              </div>
            </div>
            <div className="bg-amber-50 dark:bg-amber-900/20 rounded-lg p-4 border border-amber-200 dark:border-amber-800">
              <div className="flex items-center gap-3">
                <FaFolderOpen className="text-amber-500 text-xl" />
                <div>
                  <p className="text-xs text-amber-600 dark:text-amber-400 font-medium">Open</p>
                  <p className="text-xl font-bold text-amber-700 dark:text-amber-300">{stats.totalOpen}</p>
                </div>
              </div>
            </div>
            <div className="bg-emerald-50 dark:bg-emerald-900/20 rounded-lg p-4 border border-emerald-200 dark:border-emerald-800">
              <div className="flex items-center gap-3">
                <FaCheckCircle className="text-emerald-500 text-xl" />
                <div>
                  <p className="text-xs text-emerald-600 dark:text-emerald-400 font-medium">Completion Rate</p>
                  <p className="text-xl font-bold text-emerald-700 dark:text-emerald-300">{stats.completionRate}%</p>
                </div>
              </div>
            </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
            {/* ── CHANGE 6 cont: Show badge when filter is active ── */}
            {hasActiveFilters && (
              <span className="bg-purple-100 dark:bg-purple-900/50 text-purple-600 dark:text-purple-400 px-2 py-0.5 rounded-full text-xs font-bold">
                1
              </span>
            )}
            {filtersExpanded ? <FaChevronUp size={10} /> : <FaChevronDown size={10} />}
          </button>

          {/* Action Buttons */}
          <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={reportData.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={reportData.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={reportData.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={reportData.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>

        {/* ── CHANGE 7: Expandable Filters — replaced placeholder with real filter UI ── */}
        {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">
              {/* Technical Department Filter */}
              <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 → show locked/read-only field */}
                {!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-purple-400 flex-shrink-0"></span>
                    {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 → show 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-purple-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  >
                    <option value="">
                      {isAdmin ? 'All Departments' : 'Select Department'}
                    </option>
                    {/* Admin sees all options (passed from parent); non-admin sees only permitted ones */}
                    {/* {permittedIssueTypes.map(type => ( */}
                    {(isAdmin ? allIssueTypes : permittedIssueTypes).map(type => (
                      <option key={type} value={type}>{type}</option>
                    ))}
                  </select>
                )}
              </div>

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

              {/* Clear filter button — only shown to admins (non-admins can't clear permission filter) */}
              <div className="flex items-end">
                {isAdmin && (
                  <button
                    onClick={() => setFilterWorkOrderType('')}
                    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>
          </div>
        )}
      </div>

      {/* Content */}
      <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-purple-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 && reportData.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">
              No technicians have been assigned to work orders yet.
            </p>
          </div>
        )}

        {/* Data Table */}
        {!loading && !error && reportData.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-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap ${
                          col.fieldtype === 'Int' ? 'text-center' : 'text-left'
                        }`}
                        style={{ minWidth: col.width || 120 }}
                      >
                        {col.label}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                  {reportData.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);

                        if (col.fieldname === 'assigned_technician') {
                          return (
                            <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
                              <div className="flex items-center gap-2">
                                <div className="w-8 h-8 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
                                  <FaHardHat className="text-purple-500 dark:text-purple-400" size={14} />
                                </div>
                                <span className="text-sm font-medium text-gray-800 dark:text-gray-200">
                                  {formattedValue}
                                </span>
                              </div>
                            </td>
                          );
                        }

                        if (col.fieldname === 'total') {
                          return (
                            <td key={colIndex} className="px-4 py-3 text-center whitespace-nowrap">
                              <span className="inline-flex items-center justify-center min-w-[40px] px-3 py-1 rounded-full text-sm font-bold bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300">
                                {formattedValue}
                              </span>
                            </td>
                          );
                        }

                        if (col.fieldname === 'completed') {
                          return (
                            <td key={colIndex} className="px-4 py-3 text-center whitespace-nowrap">
                              <span className="inline-flex items-center justify-center min-w-[40px] px-3 py-1 rounded-full text-sm font-bold bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300">
                                {formattedValue}
                              </span>
                            </td>
                          );
                        }

                        if (col.fieldname === 'in_progress') {
                          return (
                            <td key={colIndex} className="px-4 py-3 text-center whitespace-nowrap">
                              <span className="inline-flex items-center justify-center min-w-[40px] px-3 py-1 rounded-full text-sm font-bold bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300">
                                {formattedValue}
                              </span>
                            </td>
                          );
                        }

                        if (col.fieldname === 'open') {
                          return (
                            <td key={colIndex} className="px-4 py-3 text-center whitespace-nowrap">
                              <span className="inline-flex items-center justify-center min-w-[40px] px-3 py-1 rounded-full text-sm font-bold bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300">
                                {formattedValue}
                              </span>
                            </td>
                          );
                        }

                        return (
                          <td
                            key={colIndex}
                            className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300"
                          >
                            {formattedValue}
                          </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 {reportData.length} technician{reportData.length !== 1 ? 's' : ''}
            {/* ── CHANGE 6 cont: Show active department in footer ── */}
            {filterWorkOrderType && (
              <span className="ml-2 text-purple-600 dark:text-purple-400">
                · {filterWorkOrderType}
              </span>
            )}
            {stats.totalWorkOrders > 0 && (
              <span className="ml-2 text-purple-600 dark:text-purple-400">
                • Total: {stats.totalWorkOrders} work orders
                • <span className="text-green-600">{stats.totalCompleted} completed</span>
                • <span className="text-blue-600">{stats.totalInProgress} in progress</span>
                • <span className="text-amber-600">{stats.totalOpen} open</span>
              </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 TechnicianWorkOrderSummaryReportModal;