"use client";
import React, { useState, useRef, useEffect } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import {
  EventInput,
  EventContentArg,
} from "@fullcalendar/core";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import { fetchHolidays } from "@/store/slices/holidaySlice";
import { fetchProjects } from "@/store/slices/projectSlice";
import { fetchSprints } from "@/store/slices/sprintSlice";
import { fetchMilestones } from "@/store/slices/milestoneSlice";
import { fetchTasks } from "@/store/slices/taskSlice";
import { fetchLeaves } from "@/store/slices/leaveSlice";

interface CalendarEvent extends EventInput {
  extendedProps: {
    calendar: string;
    tooltip?: string;
  };
}

const Calendar: React.FC = () => {
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [filters, setFilters] = useState({
    projects: true,
    sprints: false,
    milestones: false,
    tasks: false,
    holidays: true,
    leaves: true,
  });
  const calendarRef = useRef<FullCalendar>(null);
  const dispatch = useAppDispatch();

  useEffect(() => {
    dispatch(fetchHolidays({}));
    dispatch(fetchProjects({ limit: 100 }));
    dispatch(fetchSprints({ limit: 100 }));
    dispatch(fetchMilestones({ limit: 100 }));
    dispatch(fetchTasks({ limit: 100 }));
    dispatch(fetchLeaves({ limit: 100 }));
  }, [dispatch]);

  const projects = useAppSelector((state) => state.projects.projects);
  const sprints = useAppSelector((state) => state.sprints.sprints);
  const milestones = useAppSelector((state) => state.milestones.milestones);
  const tasks = useAppSelector((state) => state.tasks.tasks);
  const holidays = useAppSelector((state: any) => state.holidays?.holidays || []);

  const leaves = useAppSelector((state: any) => state.leaves?.leaves || []);

  useEffect(() => {
    const dynamicEvents: CalendarEvent[] = [];

    const splitEventByWeekdays = (
      id: string,
      title: string,
      startDateStr: string,
      endDateStr: string | undefined,
      extendedProps: any,
      skipWeekends: boolean = true
    ): CalendarEvent[] => {
      if (!endDateStr) {
        return [{ id, title, start: startDateStr, allDay: true, extendedProps }];
      }

      const formatLocalYYYYMMDD = (d: Date) => {
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      const events: CalendarEvent[] = [];
      let currentStart = new Date(startDateStr);
      const end = new Date(endDateStr);
      
      currentStart.setHours(0, 0, 0, 0);
      end.setHours(0, 0, 0, 0);

      if (currentStart > end) {
        return [{ id, title, start: startDateStr, end: endDateStr, allDay: true, extendedProps }];
      }

      let segmentStart: Date | null = null;
      let loopDate = new Date(currentStart);
      let segmentIndex = 0;

      while (loopDate <= end) {
        const day = loopDate.getDay();
        const isWeekend = day === 0 || day === 6;

        if (!skipWeekends || !isWeekend) {
          if (!segmentStart) {
            segmentStart = new Date(loopDate);
          }
        } else {
          if (segmentStart) {
            const segmentEnd = new Date(loopDate); 
            events.push({
              id: `${id}-${segmentIndex++}`,
              title,
              start: formatLocalYYYYMMDD(segmentStart),
              end: formatLocalYYYYMMDD(segmentEnd),
              allDay: true,
              extendedProps
            });
            segmentStart = null;
          }
        }
        loopDate.setDate(loopDate.getDate() + 1);
      }

      if (segmentStart) {
        events.push({
          id: `${id}-${segmentIndex}`,
          title,
          start: formatLocalYYYYMMDD(segmentStart),
          end: formatLocalYYYYMMDD(loopDate),
          allDay: true,
          extendedProps
        });
      }

      return events;
    };

    // Map Projects (Primary color)
    if (filters.projects) {
      projects?.forEach(p => {
        dynamicEvents.push(...splitEventByWeekdays(
          `PROJ-${p.id}`, 
          `Project: ${p.name}`, 
          p.startDate, 
          p.endDate, 
          { calendar: "Primary" }
        ));
      });
    }

    // Map Milestones (Warning color)
    if (filters.milestones) {
      milestones?.forEach(m => {
        dynamicEvents.push(...splitEventByWeekdays(
          `MILE-${m.id}`,
          `Milestone: ${m.name}`,
          m.startDate,
          m.dueDate,
          { calendar: "Warning" }
        ));
      });
    }

    // Map Sprints (Success color)
    if (filters.sprints) {
      sprints?.forEach(s => {
        dynamicEvents.push(...splitEventByWeekdays(
          `SPR-${s.id}`,
          `Sprint: ${s.name}`,
          s.startDate,
          s.endDate,
          { calendar: "Success" }
        ));
      });
    }

    // Map Tasks (Danger color - typically single day deadline)
    if (filters.tasks) {
      tasks?.forEach(t => {
        dynamicEvents.push({
          id: `TSK-${t.id}`,
          title: `Task Due: ${t.title}`,
          start: t.dueDate,
          allDay: true,
          extendedProps: { calendar: "Danger" }
        });
      });
    }

    // Map Holidays (DarkBlue color for WEEK_OFF, Info color for HOLIDAY)
    if (filters.holidays) {
      holidays.forEach((h: any) => {
        const isWeekOff = h.type === "WEEK_OFF";
        dynamicEvents.push(...splitEventByWeekdays(
          `HOL-${h.id}`,
          isWeekOff ? `Week-off\n${h.title === 'Week-off' ? 'Full day' : h.title || 'Full day'}` : `Holiday\n${h.title}`,
          h.startDate,
          h.endDate,
          { calendar: isWeekOff ? "DarkBlue" : "Info" },
          false // skipWeekends = false
        ));
      });
    }

    // Week-offs (Only Sundays now, Saturdays are custom)
    dynamicEvents.push({
      id: "WEEK-OFFS",
      title: "Week-off\nFull day",
      daysOfWeek: [0], // Sunday = 0
      allDay: true,
      extendedProps: { calendar: "DarkBlue" }
    });

    // Map Leaves (Secondary color - Purple)
    if (filters.leaves) {
      leaves.forEach((l: any) => {
        const start = l.fromDate || l.leaveDate;
        const end = l.toDate || l.leaveDate;
        if (start) {
          dynamicEvents.push({
            id: `LEAVE-${l.id}`,
            title: `Leave: ${l.applicantName || l.user?.firstName || 'Unknown'}`,
            start: start,
            end: end,
            allDay: true,
            extendedProps: { 
              calendar: "Secondary",
              tooltip: `Leave: ${l.applicantName || l.user?.firstName || 'Unknown'}\nReason: ${l.reason || l.leaveType || 'N/A'}\nStatus: ${l.status || 'N/A'}`
            } 
          });
        }
      });
    }

    setEvents(dynamicEvents);
  }, [projects, sprints, milestones, tasks, holidays, leaves, filters]);

  const handleFilterChange = (filterName: keyof typeof filters) => {
    setFilters(prev => ({
      ...prev,
      [filterName]: !prev[filterName]
    }));
  };

  return (
      <>
        <div className="flex flex-wrap gap-2 p-1 mb-5">
          <button
            onClick={() => handleFilterChange('projects')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.projects ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Projects
          </button>
          
          <button
            onClick={() => handleFilterChange('milestones')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.milestones ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Milestones
          </button>

          <button
            onClick={() => handleFilterChange('sprints')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.sprints ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Sprints
          </button>

          <button
            onClick={() => handleFilterChange('tasks')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.tasks ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Tasks
          </button>

          <button
            onClick={() => handleFilterChange('holidays')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.holidays ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Holidays
          </button>

          <button
            onClick={() => handleFilterChange('leaves')}
            className={`text-sm font-medium transition-colors px-4 py-2 rounded-lg w-full sm:w-auto ${filters.leaves ? 'border-2 border-brand-950 text-brand-950 bg-white shadow-sm' : 'border border-gray-200 text-brand-900 bg-white hover:bg-gray-50'}`}
          >
            Leaves
          </button>
        </div>

        <div className="border border-gray-200 rounded-lg">
          <div className="custom-calendar">
            <FullCalendar
              ref={calendarRef}
              plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
              initialView="dayGridMonth"
              headerToolbar={{
                left: "prev,next",
                center: "title",
                right: "dayGridMonth,timeGridWeek,timeGridDay",
              }}
              events={events}
              selectable={false}
              eventContent={renderEventContent}
            />
          </div>
        </div>
      </>
  );
};

const renderEventContent = (eventInfo: EventContentArg) => {
  const calendarType = eventInfo.event.extendedProps.calendar;
  
  if (calendarType === "DarkBlue") {
    // For Week-offs or DarkBlue events (as requested in the screenshot)
    return (
      <div
        title={eventInfo.event.extendedProps?.tooltip || eventInfo.event.title}
        className="flex flex-col items-center justify-center w-full h-full bg-[#1E293B] text-white p-2 rounded-sm leading-tight text-center overflow-hidden"
      >
        {eventInfo.event.title.split('\n').map((line, idx) => (
          <div key={idx} className={`text-xs ${idx === 0 ? 'font-medium' : 'text-gray-300 mt-0.5'} truncate text-ellipsis w-full whitespace-nowrap`}>
            {line}
          </div>
        ))}
      </div>
    );
  }

  const colorClass = `fc-bg-${calendarType?.toLowerCase() || 'primary'}`;
  return (
    <div
      title={eventInfo.event.extendedProps?.tooltip || eventInfo.event.title}
      className={`event-fc-color flex items-center fc-event-main ${colorClass} p-1.5 rounded-sm w-full overflow-hidden`}
    >
      <div className="fc-daygrid-event-dot mr-1"></div>
      {eventInfo.timeText && <div className="fc-event-time mr-1 font-medium">{eventInfo.timeText}</div>}
      <div className="fc-event-title truncate text-ellipsis whitespace-nowrap font-medium">{eventInfo.event.title}</div>
    </div>
  );
};

export default Calendar;
