import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAssetMaintenanceLogs } from '../hooks/useAssetMaintenance';
import { usePMSchedules } from '../hooks/usePMSchedule';
import { FaCheckCircle, FaClock, FaExclamationTriangle, FaChevronLeft, FaChevronRight, FaCalendarAlt } from 'react-icons/fa';

interface MaintenanceCalendarProps {
  month?: number;
  year?: number;
  filters?: Record<string, any>;
  viewType?: 'maintenance-log' | 'ppm-planner';
  timeView?: 'day-month' | 'year';
}

const MaintenanceCalendar: React.FC<MaintenanceCalendarProps> = ({ 
  month: initialMonth, 
  year: initialYear,
  filters: externalFilters = {},
  viewType = 'maintenance-log',
  timeView = 'day-month'
}) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const today = new Date();
  const [currentMonth, setCurrentMonth] = useState(initialMonth ?? today.getMonth());
  const [currentYear, setCurrentYear] = useState(initialYear ?? today.getFullYear());

  // Fetch maintenance logs for current and next month
  const startDate = new Date(currentYear, currentMonth, 1).toISOString().split('T')[0];
  const endDate = new Date(currentYear, currentMonth + 1, 0).toISOString().split('T')[0];
  
  // Memoize external filters to prevent object reference changes
  const externalFiltersJson = JSON.stringify(externalFilters);
  const stableExternalFilters = useMemo(() => externalFilters, [externalFiltersJson]);
  
  // Combine date filter with external filters
  const combinedFilters = useMemo(() => ({
    due_date: ['between', [startDate, endDate]],
    ...stableExternalFilters
  }), [startDate, endDate, stableExternalFilters]);
  
  // Stable empty filters object for PPM Planner
  const emptyFilters = useMemo(() => ({}), []);
  const emptyPermissionFilters = useMemo(() => ({}), []);
  
  const { logs, loading: logsLoading } = useAssetMaintenanceLogs(
    viewType === 'maintenance-log' ? combinedFilters : emptyFilters,
    viewType === 'maintenance-log' ? 1000 : 0,
    0,
    'due_date asc'
  );

  // Fetch PM Schedules (PPM Planners) using the custom API - only when viewType is ppm-planner
  const { pmSchedules, loading: pmLoading, error: pmError } = usePMSchedules(
    viewType === 'ppm-planner' ? stableExternalFilters : emptyFilters,
    1000,
    0,
    'creation desc',
    emptyPermissionFilters
  );

  const loading = viewType === 'maintenance-log' ? logsLoading : pmLoading;

  // Filter logs for current month - MUST be defined before being used in useEffect
  const currentMonthLogs = useMemo(() => {
    if (viewType === 'maintenance-log') {
      return logs.filter(log => {
        if (!log.due_date) return false;
        const logDate = new Date(log.due_date);
        return logDate.getMonth() === currentMonth && logDate.getFullYear() === currentYear;
      });
    } else {
      // Filter PM Schedules by month - use due_date (like maintenance logs) to determine which month to show
      const filtered = pmSchedules.filter(schedule => {
        // Use due_date as primary field (when maintenance is actually due)
        // Fallback to start_date if due_date is not available
        const dateToUse = schedule.due_date || schedule.start_date;
        
        if (!dateToUse) return false;
        
        // Parse date string and create date at local midnight to avoid timezone issues
        const [year, month, day] = dateToUse.split('-').map(Number);
        const scheduleDate = new Date(year, month - 1, day);
        
        // Check if the schedule date matches the current month and year
        const matches = scheduleDate.getMonth() === currentMonth && scheduleDate.getFullYear() === currentYear;
        
        return matches;
      });
      
      return filtered;
    }
  }, [logs, pmSchedules, currentMonth, currentYear, viewType]);

  // Debug: Log PM Schedules when viewType is ppm-planner
  useEffect(() => {
    if (viewType === 'ppm-planner' && !pmLoading) {
      console.log('=== PPM PLANNER DEBUG ===');
      console.log('[MaintenanceCalendar] Viewing Month:', currentMonth + 1, 'Year:', currentYear);
      console.log('[MaintenanceCalendar] Total PM Schedules fetched:', pmSchedules.length);
      console.log('[MaintenanceCalendar] Filtered for current month:', currentMonthLogs.length);
      
      if (currentMonthLogs.length > 0) {
        console.log('[MaintenanceCalendar] Schedules showing in this month:');
        currentMonthLogs.forEach((s: any) => {
          console.log(`  - ${s.name}: due_date=${s.due_date}, start_date=${s.start_date}`);
        });
      } else {
        console.log('[MaintenanceCalendar] No schedules match this month.');
        console.log('[MaintenanceCalendar] Due dates in fetched data:');
        pmSchedules.slice(0, 5).forEach((s: any) => {
          const dateToUse = s.due_date || s.start_date;
          console.log(`  - ${s.name}: due_date=${s.due_date}, start_date=${s.start_date}, will show in: ${dateToUse ? (() => {
            const [y, m] = dateToUse.split('-').map(Number);
            return `${m}/${y}`;
          })() : 'unknown'}`);
        });
        console.log('[MaintenanceCalendar] TIP: Navigate to the month where due_dates match to see schedules.');
      }
      console.log('=========================');
    }
  }, [viewType, pmSchedules, pmLoading, currentMonthLogs.length, currentMonth, currentYear]);

  const getStatusColor = (status: string, dueDate: string) => {
    const isOverdue = new Date(dueDate) < new Date() && status !== 'Completed';
    
    switch (status) {
      case 'Completed':
        return 'bg-green-500 text-white border-green-600';
      case 'Planned':
        return isOverdue ? 'bg-red-500 text-white border-red-600' : 'bg-yellow-500 text-white border-yellow-600';
      case 'Overdue':
        return 'bg-red-600 text-white border-red-700';
      default:
        return 'bg-gray-500 text-white border-gray-600';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'Completed':
        return <FaCheckCircle className="text-green-500" size={12} />;
      case 'Planned':
        return <FaClock className="text-yellow-500" size={12} />;
      case 'Overdue':
        return <FaExclamationTriangle className="text-red-500" size={12} />;
      default:
        return null;
    }
  };

  // Generate calendar days
  const firstDay = new Date(currentYear, currentMonth, 1).getDay();
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
  const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

  const navigateMonth = (direction: number) => {
    if (direction > 0) {
      if (currentMonth === 11) {
        setCurrentMonth(0);
        setCurrentYear(currentYear + 1);
      } else {
        setCurrentMonth(currentMonth + 1);
      }
    } else {
      if (currentMonth === 0) {
        setCurrentMonth(11);
        setCurrentYear(currentYear - 1);
      } else {
        setCurrentMonth(currentMonth - 1);
      }
    }
  };

  const getLogsForDay = (day: number) => {
    if (viewType === 'maintenance-log') {
      return currentMonthLogs.filter(log => {
        if (!log.due_date) return false;
        const logDate = new Date(log.due_date);
        return logDate.getDate() === day;
      });
    } else {
      // For PPM Planner, show if the day matches the due_date (like maintenance logs)
      const daySchedules = currentMonthLogs.filter((schedule: any) => {
        // Use due_date as primary field (when maintenance is actually due)
        // Fallback to start_date if due_date is not available
        const dateToUse = schedule.due_date || schedule.start_date;
        
        if (!dateToUse) return false;
        
        // Parse date string and create date at local midnight
        const [year, month, dayOfMonth] = dateToUse.split('-').map(Number);
        const scheduleDate = new Date(year, month - 1, dayOfMonth);
        
        // Check if the schedule date matches the current day
        const matches = scheduleDate.getDate() === day && 
                       scheduleDate.getMonth() === currentMonth && 
                       scheduleDate.getFullYear() === currentYear;
        
        return matches;
      });
      return daySchedules;
    }
  };

  const goToToday = () => {
    setCurrentMonth(today.getMonth());
    setCurrentYear(today.getFullYear());
  };

  const monthNames = [
    t('maintenanceCalendarPage.months.january'),
    t('maintenanceCalendarPage.months.february'),
    t('maintenanceCalendarPage.months.march'),
    t('maintenanceCalendarPage.months.april'),
    t('maintenanceCalendarPage.months.may'),
    t('maintenanceCalendarPage.months.june'),
    t('maintenanceCalendarPage.months.july'),
    t('maintenanceCalendarPage.months.august'),
    t('maintenanceCalendarPage.months.september'),
    t('maintenanceCalendarPage.months.october'),
    t('maintenanceCalendarPage.months.november'),
    t('maintenanceCalendarPage.months.december'),
  ];

  const dayNames = [
    t('maintenanceCalendarPage.days.sun'),
    t('maintenanceCalendarPage.days.mon'),
    t('maintenanceCalendarPage.days.tue'),
    t('maintenanceCalendarPage.days.wed'),
    t('maintenanceCalendarPage.days.thu'),
    t('maintenanceCalendarPage.days.fri'),
    t('maintenanceCalendarPage.days.sat'),
  ];

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow h-full flex flex-col overflow-hidden">
      <div className="flex-shrink-0 flex justify-between items-center p-4 lg:p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2 lg:gap-3">
          <FaCalendarAlt className="text-blue-600 dark:text-blue-400" size={20} />
          <h2 className="text-xl lg:text-2xl font-bold text-gray-800 dark:text-white">
            {monthNames[currentMonth]} {currentYear}
          </h2>
        </div>
        <div className="flex gap-1 lg:gap-2">
          <button
            onClick={() => navigateMonth(-1)}
            className="px-2 py-2 lg:px-4 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"
            title={t('maintenanceCalendarPage.previousMonth')}
          >
            <FaChevronLeft />
          </button>
          <button
            onClick={goToToday}
            className="px-2 py-2 lg:px-4 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors text-xs lg:text-sm font-medium"
          >
            {t('maintenanceCalendarPage.today')}
          </button>
          <button
            onClick={() => navigateMonth(1)}
            className="px-2 py-2 lg:px-4 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"
            title={t('maintenanceCalendarPage.nextMonth')}
          >
            <FaChevronRight />
          </button>
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center flex-1">
          <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">
            {viewType === 'maintenance-log' ? t('maintenanceCalendarPage.loadingLogs') : t('maintenanceCalendarPage.loadingPpm')}
          </span>
        </div>
      ) : (
        <>
          <div className="flex-1 overflow-auto p-4 lg:p-6">
            <div className="grid grid-cols-7 gap-1 lg:gap-2 mb-2">
              {dayNames.map(day => (
                <div key={day} className="text-center font-semibold p-1 lg:p-2 text-gray-700 dark:text-gray-300 text-xs lg:text-sm">
                  {day}
                </div>
              ))}
            </div>
            <div className="grid grid-cols-7 gap-1 lg:gap-2 auto-rows-fr">
              {Array.from({ length: firstDay }).map((_, i) => (
                <div key={`empty-${i}`} className="p-1 lg:p-2"></div>
              ))}
              {days.map(day => {
                const dayLogs = getLogsForDay(day);
                const isToday = day === today.getDate() && 
                              currentMonth === today.getMonth() && 
                              currentYear === today.getFullYear();
                
                return (
                  <div
                    key={day}
                    className={`border rounded-lg p-1 lg:p-2 min-h-16 lg:min-h-20 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors flex flex-col ${
                      isToday ? 'border-blue-500 border-2 bg-blue-50 dark:bg-blue-900/20' : 'border-gray-200 dark:border-gray-700'
                    }`}
                  >
                    <div className={`font-semibold mb-1 text-xs lg:text-sm flex-shrink-0 ${isToday ? 'text-blue-700 dark:text-blue-300' : 'text-gray-700 dark:text-gray-300'}`}>
                      {day}
                    </div>
                    <div className="space-y-1 flex-1 overflow-hidden">
                      {dayLogs.slice(0, 2).map(item => {
                        if (viewType === 'maintenance-log') {
                          const log = item as any;
                          const isOverdue = new Date(log.due_date || '') < new Date() && log.maintenance_status !== 'Completed';
                          return (
                            <div
                              key={log.name}
                              onClick={() => navigate(`/maintenance/${log.name}`)}
                              className={`text-xs p-1 rounded border ${getStatusColor(log.maintenance_status || 'Planned', log.due_date || '')} truncate cursor-pointer hover:opacity-80 transition-opacity`}
                              title={`${log.asset_name || log.name} - ${log.maintenance_status || 'Planned'}${isOverdue ? ` ${t('maintenanceCalendarPage.overdueInTooltip')}` : ''} - ${t('maintenanceCalendarPage.clickToViewDetails')}`}
                            >
                              <div className="truncate font-medium text-xs">{log.asset_name || log.name}</div>
                            </div>
                          );
                        } else {
                          const schedule = item as any;
                          // Debug: Log schedule data to see what fields are available
                          if (import.meta.env.DEV) {
                            console.log('[MaintenanceCalendar] Schedule data:', {
                              name: schedule.name,
                              pm_for: schedule.pm_for,
                              allFields: Object.keys(schedule)
                            });
                          }
                          
                          // Display PM Name (pm_for) instead of Name, but keep name in hover tooltip
                          // Check multiple possible field names
                          const pmName = schedule.pm_for || schedule['pm_for'] || schedule['PM Name'] || null;
                          const displayText = pmName || schedule.name || t('maintenanceCalendarPage.ppmPlannerDefault');
                          const tooltipText = schedule.name 
                            ? `${schedule.name}${schedule.modality ? ` - ${schedule.modality}` : ''}${schedule.hospital ? ` - ${schedule.hospital}` : ''} - ${t('maintenanceCalendarPage.clickToViewPpmPlanner')}`
                            : t('maintenanceCalendarPage.clickToViewPpmPlanner');
                          return (
                            <div
                              key={schedule.name}
                              onClick={() => navigate(`/ppm-planner/${schedule.name}`)}
                              className="text-xs p-1 rounded border bg-purple-500 text-white border-purple-600 truncate cursor-pointer hover:opacity-80 transition-opacity"
                              title={tooltipText}
                            >
                              <div className="truncate font-medium text-xs">{displayText}</div>
                            </div>
                          );
                        }
                      })}
                      {dayLogs.length > 2 && (
                        <div className="text-xs text-gray-500 dark:text-gray-400 font-medium">
                          +{dayLogs.length - 2}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Legend & Summary - Compact Footer */}
          <div className="flex-shrink-0 border-t border-gray-200 dark:border-gray-700 p-3 lg:p-4 bg-gray-50 dark:bg-gray-900/30">
            <div className="flex flex-col lg:flex-row justify-between items-center gap-3 lg:gap-4">
              {/* Legend */}
              <div className="flex flex-wrap gap-3 lg:gap-4 items-center justify-center lg:justify-start">
                <div className="flex items-center gap-1.5">
                  <div className="w-3 h-3 bg-green-500 rounded border border-green-600"></div>
                  <span className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendCompleted')}</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="w-3 h-3 bg-yellow-500 rounded border border-yellow-600"></div>
                  <span className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendPlanned')}</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="w-3 h-3 bg-red-500 rounded border border-red-600"></div>
                  <span className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendOverdue')}</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="w-3 h-3 border-2 border-blue-500 rounded bg-blue-50 dark:bg-blue-900/20"></div>
                  <span className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendToday')}</span>
                </div>
              </div>
              
              {/* Summary */}
              <div className="flex gap-4 lg:gap-6 text-center">
                {viewType === 'maintenance-log' ? (
                  <>
                    <div>
                      <div className="text-lg lg:text-xl font-bold text-green-600 dark:text-green-400">
                        {currentMonthLogs.filter((l: any) => l.maintenance_status === 'Completed').length}
                      </div>
                      <div className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendCompleted')}</div>
                    </div>
                    <div>
                      <div className="text-lg lg:text-xl font-bold text-yellow-600 dark:text-yellow-400">
                        {currentMonthLogs.filter((l: any) => l.maintenance_status === 'Planned' && new Date(l.due_date || '') >= new Date()).length}
                      </div>
                      <div className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendPlanned')}</div>
                    </div>
                    <div>
                      <div className="text-lg lg:text-xl font-bold text-red-600 dark:text-red-400">
                        {currentMonthLogs.filter((l: any) => {
                          const dueDate = new Date(l.due_date || '');
                          return dueDate < new Date() && l.maintenance_status !== 'Completed';
                        }).length}
                      </div>
                      <div className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.legendOverdue')}</div>
                    </div>
                  </>
                ) : (
                  <div>
                    <div className="text-lg lg:text-xl font-bold text-purple-600 dark:text-purple-400">
                      {currentMonthLogs.length}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">{t('maintenanceCalendarPage.summaryPpmPlanners')}</div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default MaintenanceCalendar;



