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

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

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

const TechnicianWorkingHoursReportModal: React.FC<TechnicianWorkingHoursReportModalProps> = ({ 
  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(true);
  
  // Filter states
  const [filterFromDate, setFilterFromDate] = useState('');
  const [filterToDate, setFilterToDate] = useState('');
  const [filterWorkOrderType, setFilterWorkOrderType] = useState('');
  
  // 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]);
  
// Auto-apply permitted Issue Type or dashboard global filter as default
useEffect(() => {
  if (!isAdmin && permittedIssueTypes.length === 1) {
    setFilterWorkOrderType(permittedIssueTypes[0]);
  } else if (defaultWorkOrderType) {
    setFilterWorkOrderType(defaultWorkOrderType);
  } else {
    setFilterWorkOrderType('');
  }
}, [permittedIssueTypes, isAdmin, defaultWorkOrderType]);

  // Report name constant
  const REPORT_NAME = 'Technicians working Hours';

  /**
   * Fetch report data from Frappe API
   */
  const fetchReportData = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      // Build filters object
      const filters: Record<string, any> = {};
      if (filterFromDate) filters.from_date = filterFromDate;
      if (filterToDate) filters.to_date = filterToDate;
      // if (filterWorkOrderType) {
      //   filters.work_order_type = filterWorkOrderType;
      // } else if (!isAdmin && permittedIssueTypes.length > 0) {
      //   filters.work_order_type = permittedIssueTypes.length === 1
      //     ? permittedIssueTypes[0]
      //     : ['in', permittedIssueTypes];
      // }


      if (filterWorkOrderType) {
        filters.work_order_type = filterWorkOrderType;
      } else if (!isAdmin && permittedIssueTypes.length > 0) {
        if (permittedIssueTypes.length === 1) {
          filters.work_order_type = permittedIssueTypes[0];
        }
      // For multiple permitted types: don't send filter at all —
      // the report will return all types, then we filter 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: 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
        // if (result.message.result) {
        //   setReportData(result.message.result);
        // } else {
        //   setReportData([]);
        // }
        if (result.message.result) {
          let rows = result.message.result;
          // Client-side filter when user has 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);
    }
  }, [filterFromDate, filterToDate, 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]);

  /**
   * Clear all filters
   */
  const handleClearFilters = () => {
    setFilterFromDate('');
    setFilterToDate('');
    if (isAdmin) setFilterWorkOrderType('');
  };

  /**
   * Calculate summary statistics
   */
  const getSummaryStats = () => {
    const totalTechnicians = reportData.length;
    const totalHours = reportData.reduce((sum, row) => sum + (parseFloat(row.total_hours) || 0), 0);
    const avgHours = totalTechnicians > 0 ? totalHours / totalTechnicians : 0;
    
    return { totalTechnicians, totalHours, avgHours };
  };

  /**
   * 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] || '';
            // 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 = `technician_working_hours_${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);
      
      // Set column widths
      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, 'Technician Hours');
      
      XLSX.writeFile(workbook, `technician_working_hours_${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>Technicians Working Hours 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.hours { color: #0891B2; }
          table { width: 100%; border-collapse: collapse; font-size: 12px; }
          th { background-color: #0891B2; 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; }
          .hours-cell { font-weight: 600; color: #0891B2; }
          @media print {
            body { margin: 0; }
            table { page-break-inside: auto; }
            tr { page-break-inside: avoid; page-break-after: auto; }
          }
        </style>
      </head>
      <body>
        <h1>Technicians Working Hours Report</h1>
        <div class="meta">
          Generated on: ${new Date().toLocaleString()}
          ${filterFromDate ? ` | From: ${filterFromDate}` : ''}
          ${filterToDate ? ` | To: ${filterToDate}` : ''}
        </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 Hours</div>
            <div class="summary-value hours">${stats.totalHours.toFixed(2)}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">Average Hours</div>
            <div class="summary-value hours">${stats.avgHours.toFixed(2)}</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 = '';
                  
                  // Add class for hours column
                  if (col.fieldname === 'total_hours') {
                    className = 'hours-cell';
                    value = typeof value === 'number' ? value.toFixed(2) : value;
                  }
                  
                  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 (filterFromDate) params.append('from_date', filterFromDate);
    if (filterToDate) params.append('to_date', filterToDate);
    
    if (params.toString()) {
      url += `?${params.toString()}`;
    }
    
    window.open(url, '_blank');
  };

  /**
   * Format cell value based on fieldtype
   */
  const formatCellValue = (value: any, column: ReportColumn) => {
    if (value === null || value === undefined || value === '') return '-';
    
    switch (column.fieldtype) {
      case 'Float':
        return typeof value === 'number' ? value.toFixed(2) : value;
      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 stats = getSummaryStats();
  const hasActiveFilters = filterFromDate || filterToDate || 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-cyan-600 to-blue-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">
              <FaClock className="text-white text-xl" />
              <div>
                <h2 className="text-xl font-bold text-white">Technicians Working Hours</h2>
                <p className="text-white/70 text-sm">
                  {reportData.length} technician{reportData.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 */}
      {!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-1 md:grid-cols-3 gap-4">
            <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">
                <FaUsers className="text-blue-500 text-2xl" />
                <div>
                  <p className="text-xs text-blue-600 dark:text-blue-400 font-medium">Total Technicians</p>
                  <p className="text-2xl font-bold text-blue-700 dark:text-blue-300">{stats.totalTechnicians}</p>
                </div>
              </div>
            </div>
            <div className="bg-cyan-50 dark:bg-cyan-900/20 rounded-lg p-4 border border-cyan-200 dark:border-cyan-800">
              <div className="flex items-center gap-3">
                <FaClock className="text-cyan-500 text-2xl" />
                <div>
                  <p className="text-xs text-cyan-600 dark:text-cyan-400 font-medium">Total Hours Worked</p>
                  <p className="text-2xl font-bold text-cyan-700 dark:text-cyan-300">{stats.totalHours.toFixed(2)}</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">
                <FaUserCog className="text-purple-500 text-2xl" />
                <div>
                  <p className="text-xs text-purple-600 dark:text-purple-400 font-medium">Average Hours/Technician</p>
                  <p className="text-2xl font-bold text-purple-700 dark:text-purple-300">{stats.avgHours.toFixed(2)}</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
            {hasActiveFilters && (
              <span className="bg-cyan-100 dark:bg-cyan-900/50 text-cyan-600 dark:text-cyan-400 px-2 py-0.5 rounded-full text-xs font-bold">
                {[filterFromDate, filterToDate, filterWorkOrderType].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={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>

        {/* 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">
              {/* From Date Filter */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  From Date
                </label>
                <input
                  type="date"
                  value={filterFromDate}
                  onChange={(e) => setFilterFromDate(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-cyan-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* To Date Filter */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  To Date
                </label>
                <input
                  type="date"
                  value={filterToDate}
                  onChange={(e) => setFilterToDate(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-cyan-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* Technical Department Filter */}
            <div>
              <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                Technical Department
              </label>
              {!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-indigo-400 flex-shrink-0"></span>
                  {filterWorkOrderType}
                  <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500 uppercase">Restricted</span>
                </div>
              ) : (
                <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-cyan-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">All Departments</option>
                  {/*{(!isAdmin && permittedIssueTypes.length > 0 ? permittedIssueTypes : []).map(type => ( */}
                  {(isAdmin ? allIssueTypes : permittedIssueTypes).map(type => (
                    <option key={type} value={type}>{type}</option>
                  ))}
                </select>
              )}
            </div>

              {/* Clear Filters Button */}
              <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>
          </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-cyan-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">
              Try adjusting your date range filters
            </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-left text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap"
                        style={{ minWidth: col.width || 150 }}
                      >
                        {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);
                        
                        // Special rendering for total_hours
                        if (col.fieldname === 'total_hours') {
                          return (
                            <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
                              <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full text-sm font-semibold bg-cyan-100 dark:bg-cyan-900/30 text-cyan-700 dark:text-cyan-300">
                                <FaClock size={12} />
                                {formattedValue} hrs
                              </span>
                            </td>
                          );
                        }
                        
                        // Link to user for engineer field
                        if (col.fieldname === 'engineer' && value) {
                          return (
                            <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
                              <a
                                href={`/app/user/${value}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-cyan-600 dark:text-cyan-400 hover:underline font-medium text-sm"
                              >
                                {formattedValue}
                              </a>
                            </td>
                          );
                        }
                        
                        // Technician name with icon
                        if (col.fieldname === 'technician_name') {
                          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-gray-200 dark:bg-gray-600 flex items-center justify-center">
                                  <FaUserCog className="text-gray-500 dark:text-gray-400" size={14} />
                                </div>
                                <span className="text-sm font-medium text-gray-800 dark:text-gray-200">
                                  {formattedValue}
                                </span>
                              </div>
                            </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 {reportData.length} technician{reportData.length !== 1 ? 's' : ''}
            {hasActiveFilters && ' (filtered)'}
            {stats.totalHours > 0 && (
              <span className="ml-2 text-cyan-600 dark:text-cyan-400">
                • Total: {stats.totalHours.toFixed(2)} hours
              </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 TechnicianWorkingHoursReportModal;