import React from 'react';
import { exportReportToExcel } from '~/utils/excelExport';

interface ReportSheet {
  id: string;
  date: string;
  area: string;
  dredgerLocation: string;
  reclamationLocation: string;
  dayReport?: any;
  nightReport?: any;
}

interface ReportSheetViewModalProps {
  isOpen: boolean;
  onClose: () => void;
  sheet: ReportSheet | null;
}

export default function ReportSheetViewModal({ isOpen, onClose, sheet }: ReportSheetViewModalProps) {
  if (!isOpen || !sheet) return null;

  const handleExportExcel = async () => {
    // Export the entire sheet (both day and night reports combined)
    await exportReportToExcel(sheet);
  };

  // Helper function to parse time string (HH:MM) to minutes
  const parseTimeToMinutes = (timeStr: string): number => {
    if (!timeStr || timeStr === '00:00') return 0;
    const [hours, minutes] = timeStr.split(':').map(Number);
    return (hours || 0) * 60 + (minutes || 0);
  };

  // Helper function to format minutes back to HH:MM
  const formatMinutesToTime = (totalMinutes: number): string => {
    const hours = Math.floor(totalMinutes / 60);
    const minutes = totalMinutes % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
  };

  // Calculate stoppage statistics
  const calculateStoppageStats = () => {
    const dayStoppages = sheet.dayReport?.stoppages || [];
    const nightStoppages = sheet.nightReport?.stoppages || [];

    // Calculate total time for day shift stoppages
    const totalDayMinutes = dayStoppages.reduce((sum, stoppage) => {
      return sum + parseTimeToMinutes(stoppage.total || '00:00');
    }, 0);

    // Calculate total time for night shift stoppages
    const totalNightMinutes = nightStoppages.reduce((sum, stoppage) => {
      return sum + parseTimeToMinutes(stoppage.total || '00:00');
    }, 0);

    // Calculate total combined time
    const totalMinutes = totalDayMinutes + totalNightMinutes;

    // Calculate counted stoppages time (excluding "Brine" or "Change Shift" in notes)
    const countedDayMinutes = dayStoppages
      .filter(stoppage => {
        const note = (stoppage.note || '').toLowerCase();
        return !note.includes('brine') && !note.includes('change shift') && !note.includes('shift change');
      })
      .reduce((sum, stoppage) => {
        return sum + parseTimeToMinutes(stoppage.total || '00:00');
      }, 0);

    const countedNightMinutes = nightStoppages
      .filter(stoppage => {
        const note = (stoppage.note || '').toLowerCase();
        return !note.includes('brine') && !note.includes('change shift') && !note.includes('shift change');
      })
      .reduce((sum, stoppage) => {
        return sum + parseTimeToMinutes(stoppage.total || '00:00');
      }, 0);

    const totalCountedMinutes = countedDayMinutes + countedNightMinutes;

    return {
      totalDayTime: formatMinutesToTime(totalDayMinutes),
      totalNightTime: formatMinutesToTime(totalNightMinutes),
      totalTime: formatMinutesToTime(totalMinutes),
      countedDayTime: formatMinutesToTime(countedDayMinutes),
      countedNightTime: formatMinutesToTime(countedNightMinutes),
      totalCountedTime: formatMinutesToTime(totalCountedMinutes),
      totalMinutes,
      totalCountedMinutes
    };
  };

  const stoppageStats = calculateStoppageStats();

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onClick={onClose}></div>

        <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-7xl sm:w-full max-w-full mx-4 sm:mx-0">
          <div className="bg-white px-4 sm:px-6 pt-4 sm:pt-6 pb-4">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 space-y-2 sm:space-y-0">
              <h3 className="text-lg sm:text-xl font-bold text-gray-900">Report Sheet - {new Date(sheet.date).toLocaleDateString('en-GB')}</h3>
              <div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
                <button
                  type="button"
                  onClick={handleExportExcel}
                  className="inline-flex items-center justify-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 w-full sm:w-auto"
                >
                  <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  Export Excel
                </button>
                <button
                  type="button"
                  onClick={() => {
                    const printContent = document.getElementById('reportframe');
                    if (printContent) {
                      const printWindow = window.open('', '_blank');
                      if (printWindow) {
                        printWindow.document.write(`
                          <html>
                            <head>
                              <title>Report Sheet Print</title>
                              <style>
                                body { 
                                  font-family: Arial, sans-serif; 
                                  margin: 0; 
                                  padding: 20px; 
                                  -webkit-print-color-adjust: exact;
                                  color-adjust: exact;
                                }
                                table { border-collapse: collapse; }
                                .border-2 { border: 2px solid black; }
                                .border { border: 1px solid black; }
                                .border-t { border-top: 1px solid black; }
                                .border-r { border-right: 1px solid black; }
                                .border-black { border-color: black; }
                                .bg-green-500 { 
                                  background-color: #10b981 !important; 
                                  -webkit-print-color-adjust: exact;
                                  color-adjust: exact;
                                }
                                .text-white { color: white !important; }
                                .text-center { text-align: center; }
                                .font-bold { font-weight: bold; }
                                .font-semibold { font-weight: 600; }
                                .p-2 { padding: 8px; }
                                .p-4 { padding: 16px; }
                                .mb-2 { margin-bottom: 8px; }
                                .mb-4 { margin-bottom: 16px; }
                                .mt-1 { margin-top: 4px; }
                                .mt-4 { margin-top: 16px; }
                                .mt-6 { margin-top: 24px; }
                                .pt-1 { padding-top: 4px; }
                                .pt-2 { padding-top: 8px; }
                                .w-full { width: 100%; }
                                .h-16 { height: 64px; }
                                .mx-auto { margin-left: auto; margin-right: auto; }
                                .underline { text-decoration: underline; }
                                .text-sm { font-size: 14px; }
                                .text-lg { font-size: 18px; }
                                .min-h-[100px] { min-height: 100px; }
                                @media print {
                                  body { 
                                    margin: 0; 
                                    -webkit-print-color-adjust: exact;
                                    color-adjust: exact;
                                  }
                                  .no-print { display: none; }
                                  .bg-green-500 { 
                                    background-color: #10b981 !important; 
                                    -webkit-print-color-adjust: exact;
                                    color-adjust: exact;
                                  }
                                  .text-white { color: white !important; }
                                }
                              </style>
                            </head>
                            <body>
                              ${printContent.innerHTML}
                            </body>
                          </html>
                        `);
                        printWindow.document.close();
                        printWindow.print();
                        printWindow.close();
                      }
                    }
                  }}
                  className="inline-flex items-center justify-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 w-full sm:w-auto"
                >
                  <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                  </svg>
                  Print
                </button>
                <button
                  type="button"
                  onClick={onClose}
                  className="bg-white rounded-md text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>

            {/* Combined Report Sheet Layout */}
            <div id="reportframe" className="max-h-[80vh] overflow-y-auto bg-white p-2 sm:p-6 border border-gray-300" style={{ fontFamily: 'Arial, sans-serif' }}>
              <ReportSheetHeader sheet={sheet} />
              <ReportSheetInfo sheet={sheet} />
              <ReportSheetDredgerSection sheet={sheet} />
              <ReportSheetLocationData sheet={sheet} />
              <ReportSheetPipelineLength sheet={sheet} />

              {/* Day Shift Section */}
              {sheet.dayReport && (
                <>
                  <ReportSheetShiftHeader shift="day" />
                  <ReportSheetEquipmentStats report={sheet.dayReport} />
                  <ReportSheetTimeSheet report={sheet.dayReport} />
                  <ReportSheetStoppages report={sheet.dayReport} />
                  <ReportSheetNotes report={sheet.dayReport} />
                </>
              )}

              {/* Night Shift Section */}
              {sheet.nightReport && (
                <>
                  <ReportSheetShiftHeader shift="night" />
                  <ReportSheetEquipmentStats report={sheet.nightReport} />
                  <ReportSheetTimeSheet report={sheet.nightReport} />
                  <ReportSheetStoppages report={sheet.nightReport} />
                  <ReportSheetNotes report={sheet.nightReport} />
                </>
              )}

              <ReportSheetFooter />
            </div>

            {/* Summary Statistics Section */}
            <div className="mt-6 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-200 p-6">
              <h4 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                <svg className="w-5 h-5 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
                Stoppage Summary Statistics
              </h4>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                {/* Total Stoppage Time */}
                <div className="bg-white rounded-lg p-4 shadow-sm border border-gray-200">
                  <h5 className="text-sm font-medium text-gray-600 mb-3 uppercase tracking-wide">Total Stoppage Time</h5>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-700">Day Shift:</span>
                      <span className="text-lg font-semibold text-blue-600 font-mono">{stoppageStats.totalDayTime}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-700">Night Shift:</span>
                      <span className="text-lg font-semibold text-purple-600 font-mono">{stoppageStats.totalNightTime}</span>
                    </div>
                    <div className="border-t pt-2 mt-2">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium text-gray-800">Total:</span>
                        <span className="text-xl font-bold text-gray-900 font-mono">{stoppageStats.totalTime}</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Counted Stoppage Time */}
                <div className="bg-white rounded-lg p-4 shadow-sm border border-gray-200">
                  <h5 className="text-sm font-medium text-gray-600 mb-3 uppercase tracking-wide">Counted Stoppage Time</h5>
                  <div className="text-xs text-gray-500 mb-3">
                    {/* (Excluding "Brine" & "Change Shift") */}
                  </div>
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-700">Day Shift:</span>
                      <span className="text-lg font-semibold text-green-600 font-mono">{stoppageStats.countedDayTime}</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-700">Night Shift:</span>
                      <span className="text-lg font-semibold text-orange-600 font-mono">{stoppageStats.countedNightTime}</span>
                    </div>
                    <div className="border-t pt-2 mt-2">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium text-gray-800">Total:</span>
                        <span className="text-xl font-bold text-red-600 font-mono">{stoppageStats.totalCountedTime}</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Time Analysis */}
                <div className="bg-white rounded-lg p-4 shadow-sm border border-gray-200">
                  <h5 className="text-sm font-medium text-gray-600 mb-3 uppercase tracking-wide">Time Analysis</h5>
                  <div className="space-y-3">
                    <div>
                      <div className="flex justify-between items-center mb-1">
                        <span className="text-sm text-gray-700">Counted Rate:</span>
                        <span className="text-sm font-medium text-gray-900">
                          {stoppageStats.totalMinutes > 0
                            ? `${Math.round((stoppageStats.totalCountedMinutes / stoppageStats.totalMinutes) * 100)}%`
                            : '0%'
                          }
                        </span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-gradient-to-r from-green-400 to-blue-500 h-2 rounded-full transition-all duration-300"
                          style={{
                            width: stoppageStats.totalMinutes > 0
                              ? `${(stoppageStats.totalCountedMinutes / stoppageStats.totalMinutes) * 100}%`
                              : '0%'
                          }}
                        ></div>
                      </div>
                    </div>

                    <div className="text-xs text-gray-600 bg-gray-50 p-2 rounded">
                      <div className="flex justify-between">
                        <span>Excluded Time:</span>
                        <span className="font-medium font-mono">
                          {formatMinutesToTime(stoppageStats.totalMinutes - stoppageStats.totalCountedMinutes)}
                        </span>
                      </div>
                    </div>

                    {/* <div className="text-xs text-gray-600 bg-blue-50 p-2 rounded">
                      <div className="flex justify-between">
                        <span>Avg per Day:</span>
                        <span className="font-medium font-mono">
                          {formatMinutesToTime(Math.round(stoppageStats.totalCountedMinutes / 2))}
                        </span>
                      </div>
                    </div> */}
                  </div>
                </div>
              </div>

              {/* Additional Info */}
              <div className="mt-4 p-3 bg-blue-100 rounded-lg">
                <p className="text-sm text-blue-800">
                  <svg className="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <strong>Note:</strong> Counted stoppage time excludes entries with "Brine" or "Change Shift" in the notes field,
                  as these are typically planned operational activities rather than unplanned stoppages. Times are displayed in HH:MM format.
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Header Section Component
function ReportSheetHeader({ sheet }: { sheet: ReportSheet }) {
  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse">
        <tbody>
          <tr>
            <td className=" p-2 text-center border-r border-black" style={{ width: '25%' }}>
              <img
                src="/logo03.png"
                alt="Company Logo"
                className="h-16 mx-auto"
                onError={(e) => {
                  e.currentTarget.style.display = 'none';
                }}
              />
            </td>
            <td className="border-r border-l border-black p-2 text-center font-bold text-lg" style={{ width: '50%' }}>
              <div>Reclamation Work Diary</div>
              <div className="border-t border-black mt-1 pt-1">QF-3.6.1-08</div>
              <div className="border-t border-black mt-1 pt-1">Rev. 1.0</div>
            </td>
            <td className="p-2 text-center border-l border-black" style={{ width: '25%' }}>
              <img
                src="/logo-light.png"
                alt="Arab Potash Logo"
                className="h-16 mx-auto"
                onError={(e) => {
                  e.currentTarget.style.display = 'none';
                }}
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Report Info Component
function ReportSheetInfo({ sheet }: { sheet: ReportSheet }) {
  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse">
        <tbody>
          <tr>
            <td className="border-r border-black p-2 font-semibold" style={{ width: '15%' }}>Date:</td>
            <td className="border-r border-black p-2" style={{ width: '35%' }}>
              {new Date(sheet.date).toLocaleDateString('en-GB')}
            </td>
            <td className="border-r border-black p-2 font-semibold" style={{ width: '20%' }}> Report No. </td>
            <td className="p-2" style={{ width: '30%' }}>{sheet.id}</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Dredger Section Component
function ReportSheetDredgerSection({ sheet }: { sheet: ReportSheet }) {
  return (
    <div className="text-center font-bold text-lg mb-2 underline">
      {sheet.area} Dredger
    </div>
  );
}

// Location Data Component (using data from either available report)
function ReportSheetLocationData({ sheet }: { sheet: ReportSheet }) {
  const report = sheet.dayReport || sheet.nightReport;
  if (!report) return null;

  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse text-sm">
        <tbody>
          <tr>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black" style={{ width: '25%' }}>
              Dredger Location
            </td>
            <td className="p-2 border-r border-black text-center" style={{ width: '25%' }}>
              {report.dredgerLocation.name}
            </td>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black" style={{ width: '25%' }}>
              Dredger Line Length
            </td>
            <td className="p-2 text-center" style={{ width: '25%' }}>
              {report.dredgerLineLength}
            </td>
          </tr>
          <tr>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black border-t border-black">
              Reclamation Location
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.reclamationLocation.name}
            </td>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black border-t border-black">
              Shore Connection
            </td>
            <td className="p-2 border-t border-black text-center">
              {report.shoreConnection}
            </td>
          </tr>
          <tr>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black border-t border-black">
              Reclamation Height
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.reclamationHeight?.base || 0}m - {(report.reclamationHeight?.extra + report.reclamationHeight?.base || 0 || 0)}m
            </td>
            <td className="p-2 border-r border-black border-t border-black" colSpan={2}></td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Pipeline Length Component (using data from either available report)
function ReportSheetPipelineLength({ sheet }: { sheet: ReportSheet }) {
  const report = sheet.dayReport || sheet.nightReport;
  if (!report) return null;

  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse text-sm">
        <tbody>
          <tr>
            <td className="bg-green-500 text-white p-2 font-semibold border-r border-black" rowSpan={2}>
              Pipeline Length "from Shore Connection"
            </td>
            <td className="p-2 border-r border-black text-center font-semibold">Main</td>
            <td className="p-2 border-r border-black text-center font-semibold">extension</td>
            <td className="p-2 border-r border-black text-center font-semibold">total</td>
            <td className="p-2 border-r border-black text-center font-semibold">Reserve</td>
            <td className="p-2 border-r border-black text-center font-semibold">extension</td>
            <td className="p-2 text-center font-semibold">total</td>
          </tr>
          <tr>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.pipelineLength?.main || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.pipelineLength?.ext1 || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {(report.pipelineLength?.main || 0) + (report.pipelineLength?.ext1 || 0)}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.pipelineLength?.reserve || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.pipelineLength?.ext2 || 0}
            </td>
            <td className="p-2 border-t border-black text-center">
              {(report.pipelineLength?.reserve || 0) + (report.pipelineLength?.ext2 || 0)}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Shift Header Component
function ReportSheetShiftHeader({ shift }: { shift: string }) {
  return (
    <div className="bg-green-500 text-white p-2 text-center font-bold mb-2 mt-6">
      {shift.charAt(0).toUpperCase() + shift.slice(1)} Shift
    </div>
  );
}

// Equipment Statistics Component
function ReportSheetEquipmentStats({ report }: { report: any }) {
  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse text-sm">
        <tbody>
          <tr>
            <td className="p-2 border-r border-black text-center font-semibold">Dozers</td>
            <td className="p-2 border-r border-black text-center font-semibold">Exc.</td>
            <td className="p-2 border-r border-black text-center font-semibold">Loader</td>
            <td className="p-2 border-r border-black text-center font-semibold">Foreman</td>
            <td className="p-2 text-center font-semibold">Laborer</td>
          </tr>
          <tr>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.stats?.Dozers || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.stats?.Exc || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.stats?.Loaders || 0}
            </td>
            <td className="p-2 border-r border-black border-t border-black text-center">
              {report.stats?.Foreman || ''}
            </td>
            <td className="p-2 border-t border-black text-center">
              {report.stats?.Laborer || 0}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

// Time Sheet Component
function ReportSheetTimeSheet({ report }: { report: any }) {
  return (
    <div className="border-2 border-black mb-4">
      <table className="w-full border-collapse text-sm">
        <thead>
          <tr>
            <td className="p-2 border-r border-black text-center font-semibold" rowSpan={2}>Time Sheet</td>
            <td className="p-2 border-r border-black text-center font-semibold">From</td>
            <td className="p-2 border-r border-black text-center font-semibold">To</td>
            <td className="p-2 border-r border-black text-center font-semibold">From</td>
            <td className="p-2 border-r border-black text-center font-semibold">To</td>
            <td className="p-2 border-r border-black text-center font-semibold">Total</td>
            <td className="p-2 text-center font-semibold">Reason</td>
          </tr>
        </thead>
        <tbody>
          {Array.isArray(report.timeSheet) && report.timeSheet.length > 0 ? (
            report.timeSheet.map((entry: any, index: number) => (
              <tr key={index}>
                <td className="p-2 border-r border-black border-t border-black font-semibold">
                  {entry.machine}
                </td>
                <td className="p-2 border-r border-black border-t border-black text-center">
                  {entry.from1}
                </td>
                <td className="p-2 border-r border-black border-t border-black text-center">
                  {entry.to1}
                </td>
                <td className="p-2 border-r border-black border-t border-black text-center">
                  {entry.from2}
                </td>
                <td className="p-2 border-r border-black border-t border-black text-center">
                  {entry.to2}
                </td>
                <td className="p-2 border-r border-black border-t border-black text-center">
                  {entry.total}
                </td>
                <td className="p-2 border-t border-black">
                  {entry.reason}
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td className="p-2 border-r border-black border-t border-black text-center" colSpan={7}>
                No time sheet entries
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}

// Stoppages Component
function ReportSheetStoppages({ report }: { report: any }) {
  return (
    <>
      <div className="bg-green-500 text-white p-2 text-center font-bold mb-2">
        Dredger Stoppages
      </div>
      <div className="border-2 border-black mb-4">
        <table className="w-full border-collapse text-sm">
          <thead>
            <tr>
              <td className="p-2 border-r border-black text-center font-semibold">From</td>
              <td className="p-2 border-r border-black text-center font-semibold">To</td>
              <td className="p-2 border-r border-black text-center font-semibold">Total</td>
              <td className="p-2 border-r border-black text-center font-semibold">Reason</td>
              <td className="p-2 border-r border-black text-center font-semibold">Responsible</td>
              <td className="p-2 text-center font-semibold">Notes</td>
            </tr>
          </thead>
          <tbody>
            {Array.isArray(report.stoppages) && report.stoppages.length > 0 ? (
              report.stoppages.map((entry: any, index: number) => (
                <tr key={index}>
                  <td className="p-2 border-r border-black border-t border-black text-center">
                    {entry.from}
                  </td>
                  <td className="p-2 border-r border-black border-t border-black text-center">
                    {entry.to}
                  </td>
                  <td className="p-2 border-r border-black border-t border-black text-center">
                    {entry.total}
                  </td>
                  <td className="p-2 border-r border-black border-t border-black">
                    {entry.reason}
                  </td>
                  <td className="p-2 border-r border-black border-t border-black">
                    {entry.responsible}
                  </td>
                  <td className="p-2 border-t border-black">
                    {entry.note}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td className="p-2 border-r border-black border-t border-black text-center" colSpan={6}>
                  No stoppages recorded
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}

// Notes Component
function ReportSheetNotes({ report }: { report: any }) {
  return (
    <>
      <div className="bg-green-500 text-white p-2 text-center font-bold mb-2">
        Notes & Comments
      </div>
      <div className="border-2 border-black mb-4 min-h-[100px]">
        <div className="p-4 text-center">
          {report.notes || 'No additional notes'}
        </div>
      </div>
    </>
  );
}

// Footer Component
function ReportSheetFooter() {
  return (
    <div className="text-center text-sm mt-4 border-t border-black pt-2">
      {/* موقعة لأعمال الصيانة */}
    </div>
  );
}