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,
  FaTable,
  FaArrowLeft
} from 'react-icons/fa';
import LinkField from './LinkField';

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

interface ReportFilter {
  fieldname: string;
  label: string;
  fieldtype: string;
  options?: string;
  mandatory?: number;
}

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

const WorkOrderReportModal: React.FC<WorkOrderReportModalProps> = ({ 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 [filterWorkOrderType, setFilterWorkOrderType] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  
  // Export states
  const [isExporting, setIsExporting] = useState(false);

  // Report name constant
  const REPORT_NAME = 'Work Order Data';

  /**
   * Fetch report data from Frappe API
   */
  const fetchReportData = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      // Build filters object
      const filters: Record<string, any> = {};
      if (filterWorkOrderType) filters.work_order_type = filterWorkOrderType;
      if (filterStatus) filters.repair_status = filterStatus;
      
      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([]);
        }
      }
    } catch (err) {
      console.error('Error fetching report:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch report data');
      setReportData([]);
    } finally {
      setLoading(false);
    }
  }, [filterWorkOrderType, filterStatus]);

  // 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 = () => {
    setFilterWorkOrderType('');
    setFilterStatus('');
  };

  /**
   * 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 = `work_order_report_${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) : 15 }));
      worksheet['!cols'] = colWidths;
      
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Work Order Report');
      
      XLSX.writeFile(workbook, `work_order_report_${new Date().toISOString().split('T')[0]}.xlsx`);
    } finally {
      setIsExporting(false);
    }
  };

  /**
   * Print report
   */
  const handlePrint = () => {
    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>Work Order 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; }
          table { width: 100%; border-collapse: collapse; font-size: 11px; }
          th { background-color: #4A90D9; 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: #D97706; font-weight: 500; }
          .status-completed { color: #059669; font-weight: 500; }
          .status-inprogress { color: #2563EB; font-weight: 500; }
          .priority-urgent { color: #DC2626; font-weight: 600; }
          .priority-normal { color: #6B7280; }
          @media print {
            body { margin: 0; }
            table { page-break-inside: auto; }
            tr { page-break-inside: avoid; page-break-after: auto; }
          }
        </style>
      </head>
      <body>
        <h1>Work Order Report</h1>
        <div class="meta">
          Generated on: ${new Date().toLocaleString()} | Total Records: ${reportData.length}
          ${filterWorkOrderType ? ` | Type: ${filterWorkOrderType}` : ''}
          ${filterStatus ? ` | Status: ${filterStatus}` : ''}
        </div>
        <table>
          <thead>
            <tr>
              ${columns.map(col => `<th>${col.label}</th>`).join('')}
            </tr>
          </thead>
          <tbody>
            ${reportData.map(row => `
              <tr>
                ${columns.map(col => {
                  let value = row[col.fieldname] || '-';
                  let className = '';
                  
                  // Add status classes
                  if (col.fieldname === 'repair_status') {
                    if (value.toLowerCase().includes('open')) className = 'status-open';
                    else if (value.toLowerCase().includes('completed')) className = 'status-completed';
                    else if (value.toLowerCase().includes('progress')) className = 'status-inprogress';
                  }
                  
                  // Add priority classes
                  if (col.fieldname === 'custom_priority_') {
                    if (value.toLowerCase() === 'urgent') className = 'priority-urgent';
                    else className = 'priority-normal';
                  }
                  
                  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 (filterWorkOrderType) params.append('work_order_type', filterWorkOrderType);
    if (filterStatus) params.append('repair_status', filterStatus);
    
    if (params.toString()) {
      url += `?${params.toString()}`;
    }
    
    window.open(url, '_blank');
  };

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

  /**
   * Get priority badge color
   */
  const getPriorityColor = (priority: string) => {
    switch (priority?.toLowerCase()) {
      case 'urgent':
        return 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300';
      case 'medium':
        return 'bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300';
      default:
        return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-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'
        });
      case 'Currency':
        return new Intl.NumberFormat('en-US', {
          style: 'currency',
          currency: 'SAR'
        }).format(value);
      case 'Link':
        return value;
      default:
        return String(value);
    }
  };

  if (!isOpen) return null;

  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-indigo-600 to-purple-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">
              <FaTable className="text-white text-xl" />
              <div>
                <h2 className="text-xl font-bold text-white">Work Order Report</h2>
                <p className="text-white/70 text-sm">
                  {reportData.length} record{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>

      {/* 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
            {(filterWorkOrderType || filterStatus) && (
              <span className="bg-indigo-100 dark:bg-indigo-900/50 text-indigo-600 dark:text-indigo-400 px-2 py-0.5 rounded-full text-xs font-bold">
                {[filterWorkOrderType, filterStatus].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">
              {/* Work Order Type Filter */}
            <div className="relative z-[70]">
            <LinkField
                label="Work Order Type"
                doctype="Issue Type"
                value={filterWorkOrderType}
                onChange={(val) => setFilterWorkOrderType(val)}
                placeholder="All Types"
                disabled={false}
                compact={false}
            />
            </div>

              {/* Status Filter */}
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Work Order 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-indigo-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="Work In Progress">Work In Progress</option>
                  <option value="Pending Review">Pending Review</option>
                  <option value="Completed">Completed</option>
                  <option value="Executed">Executed</option>
                  <option value="Cancelled">Cancelled</option>
                  <option value="Closed">Closed</option>
                </select>
              </div>

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

              {/* Clear Filters Button */}
              <div className="flex items-end">
                <button
                  onClick={handleClearFilters}
                  disabled={!filterWorkOrderType && !filterStatus}
                  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-indigo-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 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 || 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);
                        
                        // Special rendering for status
                        if (col.fieldname === 'repair_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 priority
                        if (col.fieldname === 'custom_priority_') {
                          return (
                            <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
                              <span className={`px-3 py-1 rounded-full text-xs font-medium ${getPriorityColor(value)}`}>
                                {formattedValue}
                              </span>
                            </td>
                          );
                        }
                        
                        // Link fields - make clickable
                        if (col.fieldtype === 'Link' && col.fieldname === 'name') {
                          return (
                            <td key={colIndex} className="px-4 py-3 whitespace-nowrap">
                              <a
                                href={`/asm_app/work-orders/${value}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-indigo-600 dark:text-indigo-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 {reportData.length} record{reportData.length !== 1 ? 's' : ''}
            {(filterWorkOrderType || filterStatus) && ' (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 WorkOrderReportModal;