"use client";

import {
  startOfMonth,
  endOfMonth,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  isSameDay,
  format,
} from "date-fns";
import { useCalendarContext } from "@/components/providers/CalendarProvider";
import DayCell from "./DayCell";

const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

export default function MonthGrid() {
  const {
    currentMonth,
    selectedDate,
    selectDate,
    events,
    googleEvents,
    calendars,
    activeCalendarIds,
  } = useCalendarContext();

  const monthStart = startOfMonth(currentMonth);
  const monthEnd = endOfMonth(currentMonth);
  const gridStart = startOfWeek(monthStart);
  const gridEnd = endOfWeek(monthEnd);
  const days = eachDayOfInterval({ start: gridStart, end: gridEnd });

  const calendarColors: Record<string, string> = {};
  for (const cal of calendars) {
    calendarColors[cal.id] = cal.color;
  }

  const filteredEvents = events.filter((e) => activeCalendarIds.has(e.calendar_id));

  const getEventsForDay = (date: Date) => {
    const dayStr = format(date, "yyyy-MM-dd");
    return filteredEvents.filter((e) => {
      const startDate = format(new Date(e.start_time), "yyyy-MM-dd");
      const endDate = format(new Date(e.end_time), "yyyy-MM-dd");
      return dayStr >= startDate && dayStr <= endDate;
    });
  };

  const getGoogleEventsForDay = (date: Date) => {
    const dayStr = format(date, "yyyy-MM-dd");
    return googleEvents.filter((e) => {
      const startDate = format(new Date(e.start_time), "yyyy-MM-dd");
      const endDate = format(new Date(e.end_time), "yyyy-MM-dd");
      return dayStr >= startDate && dayStr <= endDate;
    });
  };

  return (
    <div>
      <div className="grid grid-cols-7 mb-1">
        {WEEKDAYS.map((day) => (
          <div
            key={day}
            className="text-center text-xs font-medium text-zinc-500 dark:text-zinc-400 py-2"
          >
            {day}
          </div>
        ))}
      </div>

      <div className="grid grid-cols-7">
        {days.map((day) => (
          <DayCell
            key={day.toISOString()}
            date={day}
            currentMonth={currentMonth}
            isSelected={selectedDate ? isSameDay(day, selectedDate) : false}
            events={getEventsForDay(day)}
            googleEvents={getGoogleEventsForDay(day)}
            calendarColors={calendarColors}
            onSelect={selectDate}
          />
        ))}
      </div>
    </div>
  );
}
