"use client";

import React from "react";
import moment from "moment";
import {
  Calendar as BigCalendar,
  View as RBCView,
} from "react-big-calendar";
import "react-big-calendar/lib/css/react-big-calendar.css";
import {
  CustomDayHeader,
  CustomHeaderCell,
  CustomMonthHeader,
  EventComponent,
} from "./CalendarCells";
import YearView from "./CalendarYearView";
import { localizer } from "./calendarLocalizer";
import type { CalendarEvent, CustomView } from "./calendarTypes";
import type {
  Components,
  DateHeaderProps,
  EventWrapperProps,
} from "react-big-calendar";
import type { useCalendar } from "./useCalendar";
import { clickable } from "@/lib/a11y";


/**
 * The grid itself: react-big-calendar for day/week/month, and the hand-rolled
 * year view.
 *
 * The week view caps each day at three entries and collapses the rest into a
 * "+N more" chip, which is what `WeekEventWrapper` below is for.
 */
export default function CalendarViewArea({
  screen,
}: {
  screen: ReturnType<typeof useCalendar>;
}) {
  const {
    isRTL,
    view,
    setView,
    currentDate,
    calendarContainerRef,
    isLoading,
    events,
    handleSelectEvent,
    eventStyleGetter,
    handleNavigate,
    formats,
    setModalEvents,
    setModalDate,
    setShowEventModal,
  } = screen;

  /**
   * Week view caps each day at 3 events and collapses the rest into a "+N more".
   *
   * `EventWrapperProps<CalendarEvent>` is react-big-calendar's own prop type for
   * this slot — it was `React.FC<any>`, which is why `event.start` below was
   * unchecked. `children` is not on that interface (the library passes the
   * wrapped event element as a child), so it is intersected in.
   */
  const WeekEventWrapper = ({
    children,
    event,
  }: EventWrapperProps<CalendarEvent> & { children?: React.ReactNode }) => {
    if (view !== "week") return children;

    const slotDate = moment(event.start).startOf("day");
    const eventsForDay = events.filter((e) =>
      moment(e.start).isSame(slotDate, "day")
    );

    const index = eventsForDay.findIndex(
      (e) =>
        e.start.getTime() === event.start.getTime() &&
        e.end.getTime() === event.end.getTime()
    );

    if (index < 3) return children;

    if (index === 3) {
      const remaining = eventsForDay.length - 3;
      return (
        <div
          style={{
            background: "#fff",
            color: "#5271FF",
            borderRadius: "4px",
            padding: "2px 8px",
            cursor: "pointer",
            fontSize: "12px",
            border: "1px solid #5271FF",
            marginTop: "2px",
          }}
          /* The "+N more" chip opens the day's event list. Rendered inside
             react-big-calendar's own slot markup, so it stays a `div` and
             takes the role and key handling from `clickable`. */
          {...clickable(() => {
            setModalEvents(eventsForDay);
            setModalDate(slotDate.toDate());
            setShowEventModal(true);
          })}
        >
          +{remaining} more
        </div>
      );
    }

    // Hide all events after the 4th
    return null;
  };

  return (
    <div
      className="flex-1 overflow-auto h-[500px] md:h-[600px] lg:h-[700px]"
      ref={calendarContainerRef}
    >
      {isLoading ? (
        <div className="flex justify-center items-center h-full">
          <span>Loading events...</span>
        </div>
      ) : view === "year" ? (
        <YearView
          date={currentDate}
          localizer={localizer}
          events={events}
          onNavigate={(date) => {
            // Month headers hand back midnight on the 1st; day cells
            // hand back the specific day.
            const isMonthClick =
              date.getDate() === 1 &&
              date.getHours() === 0 &&
              date.getMinutes() === 0 &&
              date.getSeconds() === 0;

            handleNavigate(date);
            setView(isMonthClick ? "month" : "day");
          }}
          isRTL={isRTL}
        />
      ) : (
        <BigCalendar
          localizer={localizer}
          events={events}
          startAccessor="start"
          endAccessor="end"
          style={{ height: "100%" }}
          formats={formats}
          views={{ month: true, week: true, day: true }}
          view={view as "day" | "week" | "month"}
          onView={(newView: RBCView) => {
            // Only set standard views from the Calendar component
            if (newView !== "agenda") {
              setView(newView as CustomView);
            }
          }}
          date={currentDate}
          onNavigate={handleNavigate}
          eventPropGetter={eventStyleGetter}
          onSelectEvent={handleSelectEvent}
          timeslots={view === "day" || view === "week" ? 2 : 1}
          step={view === "day" || view === "week" ? 30 : 60}
          min={moment(currentDate).startOf("day").toDate()}
          max={moment(currentDate).endOf("day").toDate()}
          rtl={isRTL}
          culture={isRTL ? "ar" : "en"}
          className="custom-calendar"
          /*
           * Typed as the library's own `Components<CalendarEvent>` rather than
           * cast. The four `as any` casts this replaces were hiding a real
           * mismatch: `EventComponent` declares `title: string` while
           * react-big-calendar's `EventProps` makes it `React.ReactNode`, and
           * the header cells declared only the two props they read out of the
           * three `HeaderProps` supplies. Both are now satisfied properly, so a
           * future change to either side is checked.
           */
          components={
            {
              toolbar: () => null,
              event: EventComponent,
              timeGutterHeader: () => null,
              eventWrapper: WeekEventWrapper,
              week: { header: CustomHeaderCell },
              month: {
                dateHeader: (props: DateHeaderProps) => (
                  <CustomMonthHeader {...props} isRTL={isRTL} />
                ),
              },
              day: { header: CustomDayHeader },
            } satisfies Components<CalendarEvent>
          }
        />
      )}
    </div>
  );
}
