'use client';

import { useMemo } from 'react';
import { ScheduleCalendar } from '@/components/common/ScheduleCalendar/ScheduleCalendar';
import type { ScheduleEvent } from '@/components/common/ScheduleCalendar/types';
import type { CalendarSchedule } from './types';
import { SCHEDULE_TYPE_COLORS } from './types';

interface YearCalendarProps {
  year: number;
  schedules: CalendarSchedule[];
  onDateClick: (date: Date) => void;
}

export function YearCalendar({ year, schedules, onDateClick }: YearCalendarProps) {
  const eventsByMonth = useMemo(() => {
    const allEvents: ScheduleEvent[] = schedules.map((s) => ({
      id: s.id,
      title: s.name,
      startDate: s.startDate,
      endDate: s.endDate,
      color: SCHEDULE_TYPE_COLORS[s.type],
      data: s,
    }));

    const months: ScheduleEvent[][] = Array.from({ length: 12 }, () => []);

    for (const event of allEvents) {
      const startMonth = new Date(event.startDate).getMonth();
      const endMonth = new Date(event.endDate).getMonth();
      for (let m = startMonth; m <= endMonth; m++) {
        months[m].push(event);
      }
    }

    return months;
  }, [schedules]);

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {Array.from({ length: 12 }, (_, i) => (
        <ScheduleCalendar
          key={i}
          currentDate={new Date(year, i, 1)}
          view="month"
          availableViews={[]}
          events={eventsByMonth[i]}
          onDateClick={onDateClick}
          onEventClick={(event) => {
            const schedule = event.data as CalendarSchedule;
            if (schedule) {
              onDateClick(new Date(schedule.startDate));
            }
          }}
          maxEventsPerDay={3}
          hideNavigation
          className="h-full"
        />
      ))}
    </div>
  );
}
