"use client";

import React from "react";
import moment, { type Moment } from "moment";
import type {
  YearViewDay,
  YearViewProps,
} from "./calendarTypes";
import { clickable } from "@/lib/a11y";

// Custom Year View component to mimic Google Calendar
export default function YearView({
  date,
  localizer: loc,
  events,
  onNavigate,
  isRTL,
}: YearViewProps) {
  const currentYear = moment(date).year();
  const months = Array.from({ length: 12 }, (_, i) =>
    moment().year(currentYear).month(i)
  );

  // Function to generate the days for each month
  const generateMonthDays = (month: Moment): YearViewDay[] => {
    const daysInMonth = month.daysInMonth();
    const startOfMonth = month.clone().startOf("month");
    const firstDayOfWeek = startOfMonth.day(); // 0 for Sunday

    const days: YearViewDay[] = [];
    // Add empty placeholders for days before the 1st of the month
    for (let i = 0; i < firstDayOfWeek; i++) {
      days.push({ day: null, date: null, events: [] });
    }

    // Add the actual days of the month
    for (let i = 1; i <= daysInMonth; i++) {
      const dayMoment = month.clone().date(i);
      const dateStr = dayMoment.format("YYYY-MM-DD");

      // Events starting, ending, or spanning this date
      const dayEvents = events.filter((event) => {
        const eventStartDate = moment(event.start).format("YYYY-MM-DD");
        const eventEndDate = moment(event.end).format("YYYY-MM-DD");
        return (
          eventStartDate === dateStr ||
          eventEndDate === dateStr ||
          moment(dateStr).isBetween(eventStartDate, eventEndDate, null, "[]")
        );
      });

      days.push({
        day: i,
        date: dateStr,
        isToday: dayMoment.isSame(moment(), "day"),
        events: dayEvents.length > 0 ? dayEvents.slice(0, 4) : [],
      });
    }

    return days;
  };

  // Handle month click to navigate to month view
  const handleMonthClick = (month: Moment) => {
    onNavigate(month.clone().startOf("month").toDate());
  };

  return (
    <div className={`year-view p-4 ${isRTL ? "rtl" : "ltr"}`}>
      <h2 className="text-2xl font-semibold text-center mb-6">{currentYear}</h2>

      <div className="grid grid-cols-3 gap-6 lg:grid-cols-4 md:grid-cols-3 sm:grid-cols-2">
        {months.map((month, index) => (
          <div
            key={index}
            className="month-container border rounded-lg shadow-sm bg-white overflow-hidden hover:shadow-md cursor-pointer"
            /* The month tile navigates into the month view — the only way to
               do so from the year view, and it was mouse-only. */
            {...clickable(() => handleMonthClick(month))}
          >
            <div className="month-header p-2 bg-gray-100 text-center font-semibold">
              {loc.format(month.toDate(), "MMMM")}
            </div>

            <div className="month-days grid grid-cols-7 text-xs">
              {/* Day headers: Sun, Mon, etc. */}
              {["S", "M", "T", "W", "T", "F", "S"].map((dayName, i) => (
                <div key={i} className="day-header p-1 text-center text-gray-500">
                  {dayName}
                </div>
              ))}
              {/* Actual days */}
              {generateMonthDays(month).map((day, i) => (
                <div
                  key={i}
                  className={`day-cell p-1 text-center ${
                    !day.day ? "text-gray-300" : ""
                  } ${day.isToday ? "bg-blue-100 text-blue-700 font-bold" : ""} ${
                    day.events && day.events.length > 0 ? "has-events" : ""
                  } ${day.day ? "cursor-pointer hover:bg-gray-100" : ""}`}
                  /*
                   * Deliberately **not** given a role or a tab stop, and the
                   * jsx-a11y report on this `onClick` is the accepted
                   * consequence.
                   *
                   * The month tile this sits inside is itself the control —
                   * `clickable()` above makes it `role="button"` — and a
                   * second button nested inside a button is invalid, announced
                   * unpredictably, and would put 28-31 tab stops inside every
                   * one of twelve tiles. Picking a *specific* day is a pointer
                   * refinement of what the tile already does; the keyboard
                   * path (open this month) is the tile's, and the month view it
                   * lands on is where days are selectable one by one.
                   */
                  onClick={(e) => {
                    // Only handle click for valid days
                    if (day.day && day.date) {
                      e.stopPropagation(); // Prevent triggering the month click
                      onNavigate(new Date(day.date));
                    }
                  }}
                >
                  {day.day}
                  {day.events && day.events.length > 0 && (
                    <div className="flex justify-center mt-0.5 space-x-0.5">
                      <div className="event-dot h-1.5 w-1.5 rounded-full bg-blue-500" />
                      {day.events.length > 1 && (
                        <div className="event-dot h-1.5 w-1.5 rounded-full bg-green-500" />
                      )}
                      {day.events.length > 2 && (
                        <div className="event-dot h-1.5 w-1.5 rounded-full bg-red-500" />
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
