import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { FaCalendarAlt, FaChevronLeft, FaChevronRight, FaArrowLeft, FaCalendar } from 'react-icons/fa';
import { usePMSchedules } from '../hooks/usePMSchedule';

const YearlyPPMPlannerPage: React.FC = () => {
  const navigate = useNavigate();
  const today = new Date();
  const [startYear, setStartYear] = useState(2025);
  const [endYear, setEndYear] = useState(2030);

  // Stable empty filters object
  const emptyFilters = useMemo(() => ({}), []);
  const emptyPermissionFilters = useMemo(() => ({}), []);
  
  // Fetch all PM Schedules (PPM Planners) using the custom API
  const { pmSchedules, loading, error } = usePMSchedules(emptyFilters, 1000, 0, 'creation desc', emptyPermissionFilters);

  // Helper function to calculate if a month should show based on periodicity
  const shouldShowInMonth = (
    periodicity: string,
    dueDate: Date,
    endDate: Date,
    checkYear: number,
    checkMonth: number
  ): boolean => {
    const periodicityLower = periodicity.toLowerCase().trim();
    const dueYear = dueDate.getFullYear();
    const dueMonth = dueDate.getMonth();
    
    // Check if the check date is within the valid range (due_date to end_date)
    const checkDate = new Date(checkYear, checkMonth, 1);
    const monthEnd = new Date(checkYear, checkMonth + 1, 0, 23, 59, 59, 999);
    
    if (checkDate > endDate || monthEnd < dueDate) {
      return false; // Outside the valid date range
    }
    
    // Calculate months since due date
    const monthsSinceDue = (checkYear - dueYear) * 12 + (checkMonth - dueMonth);
    
    switch (periodicityLower) {
      case 'daily':
        // Show in the month where any day from due_date to end_date falls
        return checkDate <= endDate && monthEnd >= dueDate;
        
      case 'weekly':
        // Show in the month where any week from due_date to end_date falls
        // A week is considered to be in a month if any day of that week is in that month
        return checkDate <= endDate && monthEnd >= dueDate;
        
      case 'monthly':
        // Show every month from due_date to end_date
        return monthsSinceDue >= 0 && checkDate <= endDate;
        
      case 'quarterly':
        // Show every 3 months from due_date to end_date
        return monthsSinceDue >= 0 && monthsSinceDue % 3 === 0 && checkDate <= endDate;
        
      case 'half-yearly':
      case 'half yearly':
        // Show every 6 months from due_date to end_date
        return monthsSinceDue >= 0 && monthsSinceDue % 6 === 0 && checkDate <= endDate;
        
      case 'yearly':
      case 'annually':
        // Show in the same month every year from due_date to end_date
        return checkMonth === dueMonth && checkDate <= endDate && checkDate >= dueDate;
        
      case '2 yearly':
      case '2-yearly':
        // Show every 24 months from due_date to end_date
        return monthsSinceDue >= 0 && monthsSinceDue % 24 === 0 && checkDate <= endDate;
        
      case '3 yearly':
      case '3-yearly':
        // Show every 36 months from due_date to end_date
        return monthsSinceDue >= 0 && monthsSinceDue % 36 === 0 && checkDate <= endDate;
        
      default:
        // Unknown periodicity, show if within date range
        return checkDate <= endDate && monthEnd >= dueDate;
    }
  };

  // Group schedules by year and month - create a matrix structure
  const schedulesMatrix = useMemo(() => {
    const matrix: Record<number, Record<number, typeof pmSchedules>> = {};
    
    // Initialize matrix for all years
    for (let year = startYear; year <= endYear; year++) {
      matrix[year] = {};
      for (let month = 0; month < 12; month++) {
        matrix[year][month] = [];
      }
    }
    
    // Populate matrix with schedules
    pmSchedules.forEach(schedule => {
      // Parse dates and normalize to date-only
      let startDate: Date | null = null;
      let endDate: Date | null = null;
      let dueDate: Date | null = null;
      
      if (schedule.start_date) {
        const [year, month, day] = schedule.start_date.split('-').map(Number);
        startDate = new Date(year, month - 1, day);
      }
      
      if (schedule.end_date) {
        const [year, month, day] = schedule.end_date.split('-').map(Number);
        endDate = new Date(year, month - 1, day);
      }
      
      // Use due_date as the primary indicator - this is the starting point
      if (schedule.due_date) {
        const [year, month, day] = schedule.due_date.split('-').map(Number);
        dueDate = new Date(year, month - 1, day);
      }
      
      // If no due_date, skip this schedule (we need due_date to calculate recurring dates)
      if (!dueDate) return;
      
      // Use end_date if available, otherwise use due_date (single occurrence)
      const scheduleEndDate = endDate || dueDate;
      
      // Get periodicity (default to 'monthly' if not specified)
      const periodicity = schedule.periodicity || 'monthly';
      
      // Iterate through all years and months in the visible range
      for (let year = startYear; year <= endYear; year++) {
        for (let month = 0; month < 12; month++) {
          // Check if this month should show based on periodicity
          if (shouldShowInMonth(periodicity, dueDate, scheduleEndDate, year, month)) {
            // Check if schedule already exists in this cell (avoid duplicates)
            const exists = matrix[year][month].some(s => s.name === schedule.name);
            if (!exists) {
              matrix[year][month].push(schedule);
            }
          }
        }
      }
    });
    
    return matrix;
  }, [pmSchedules, startYear, endYear]);

  // Debug: Log PM Schedules
  useEffect(() => {
    if (!loading) {
      console.log('[YearlyPPMPlannerPage] PM Schedules count:', pmSchedules.length);
      console.log('[YearlyPPMPlannerPage] Matrix years:', startYear, 'to', endYear);
    }
  }, [pmSchedules, loading, startYear, endYear]);

  const navigateYears = (direction: number) => {
    const range = endYear - startYear + 1;
    setStartYear(prev => prev + direction);
    setEndYear(prev => prev + direction);
  };

  const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const fullMonthNames = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];

  // Generate years array
  const years = Array.from({ length: endYear - startYear + 1 }, (_, i) => startYear + i);

  return (
    <div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900 overflow-hidden">
      {/* Header */}
      <div className="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 lg:px-6">
        <div className="flex justify-between items-center">
          <div className="flex items-center gap-3">
            <button
              onClick={() => navigate('/maintenance-calendar/month-view')}
              className="p-1.5 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="Back to Month View"
            >
              <FaArrowLeft className="text-gray-600 dark:text-gray-400" size={18} />
            </button>
            <FaCalendarAlt className="text-blue-600 dark:text-blue-400" size={24} />
            <div>
              <h1 className="text-xl font-bold text-gray-800 dark:text-white">
                Site or Cluster PPM Calendar
              </h1>
              <p className="text-xs text-gray-600 dark:text-gray-400">
                View PM Schedule Generators across multiple years
              </p>
            </div>
          </div>
          <button
            onClick={() => navigate('/maintenance-calendar/month-view')}
            className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2 text-sm font-medium"
            title="Go to Month View"
          >
            <FaCalendar size={14} />
            Month
          </button>
        </div>
      </div>

      {/* Year Navigation */}
      <div className="flex-shrink-0 px-3 lg:px-4 py-2">
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 p-2">
          <div className="flex items-center justify-between">
            <button
              onClick={() => navigateYears(-1)}
              className="px-3 py-1.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg text-gray-700 dark:text-gray-300 transition-colors"
            >
              <FaChevronLeft />
            </button>
            <h2 className="text-lg font-bold text-gray-800 dark:text-white">
              {startYear} - {endYear}
            </h2>
            <button
              onClick={() => navigateYears(1)}
              className="px-3 py-1.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg text-gray-700 dark:text-gray-300 transition-colors"
            >
              <FaChevronRight />
            </button>
          </div>
        </div>
      </div>

      {/* Calendar Grid */}
      <div className="flex-1 overflow-auto px-3 pb-3 lg:px-4 lg:pb-4">
        {loading ? (
          <div className="flex items-center justify-center h-full">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
            <span className="ml-3 text-gray-600 dark:text-gray-400">Loading PPM Planners...</span>
          </div>
        ) : error ? (
          <div className="flex items-center justify-center h-full">
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
              <p className="text-red-600 dark:text-red-400">Error loading PPM Planners: {error}</p>
            </div>
          </div>
        ) : (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead className="bg-gray-100 dark:bg-gray-700 sticky top-0 z-10">
                  <tr>
                    <th className="border border-gray-300 dark:border-gray-600 px-4 py-3 text-left font-bold text-gray-800 dark:text-white bg-gray-200 dark:bg-gray-800">
                      Year/Month
                    </th>
                      {monthNames.map((month, idx) => (
                      <th
                        key={idx}
                        className="border border-gray-300 dark:border-gray-600 px-2 py-3 text-center font-semibold text-gray-800 dark:text-white min-w-[140px]"
                      >
                        {month}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {years.map(year => (
                    <tr key={year} className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
                      <td className="border border-gray-300 dark:border-gray-600 px-4 py-3 font-bold text-gray-800 dark:text-white bg-gray-50 dark:bg-gray-800/50">
                        {year}
                      </td>
                      {monthNames.map((_, monthIndex) => {
                        const cellSchedules = schedulesMatrix[year]?.[monthIndex] || [];
                        return (
                          <td
                            key={monthIndex}
                            className="border border-gray-300 dark:border-gray-600 px-2 py-2 align-top min-h-[60px]"
                          >
                            {cellSchedules.length > 0 ? (
                              <div className="space-y-1">
                                {cellSchedules.map(schedule => {
                                  // Display PM Name (pm_for) instead of Name
                                  // Check multiple possible field names
                                  const pmName = schedule.pm_for || (schedule as any).pm_for || (schedule as any)['PM Name'] || null;
                                  
                                  // Debug log for first item only
                                  if (cellSchedules.indexOf(schedule) === 0) {
                                    console.log('[YearlyCalendar] 🔍 SCHEDULE IN CELL:', {
                                      name: schedule.name,
                                      pm_for: schedule.pm_for,
                                      'pm_for (bracket)': (schedule as any)['pm_for'],
                                      allKeys: Object.keys(schedule),
                                      pmName: pmName
                                    });
                                  }
                                  
                                  const displayText = pmName || schedule.name || 'PPM Planner';
                                  
                                  // Build hover tooltip: Name, Modality, Hospital
                                  const tooltipParts: string[] = [];
                                  if (schedule.name) {
                                    tooltipParts.push(schedule.name);
                                  }
                                  if (schedule.modality) {
                                    tooltipParts.push(schedule.modality);
                                  }
                                  if (schedule.hospital) {
                                    tooltipParts.push(schedule.hospital);
                                  }
                                  const tooltipText = tooltipParts.length > 0 
                                    ? `${tooltipParts.join(' - ')} - Click to view details`
                                    : 'Click to view details';
                                  
                                  return (
                                    <div
                                      key={schedule.name}
                                      onClick={() => navigate(`/ppm-planner/${schedule.name}`)}
                                      className="text-[10px] p-1 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded cursor-pointer hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors group"
                                      title={tooltipText}
                                    >
                                      <div className="font-medium text-blue-900 dark:text-blue-300 leading-tight group-hover:underline break-words">
                                        {displayText}
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                            ) : (
                              <div className="text-xs text-gray-300 dark:text-gray-700 text-center py-1">
                                -
                              </div>
                            )}
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default YearlyPPMPlannerPage;
