"use client";

import React, { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { localizer } from "./calendarLocalizer";
import moment, { Moment } from "moment";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import "react-big-calendar/lib/css/react-big-calendar.css";
import { getCalendar } from "@/features/calendar/services/calendarApi";
import { useLanguageStore } from "@/store/languageStore";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import {
  EVENT_TYPES,
  GENERIC_TYPE_LABELS,
  LEARN_SERVE_TYPES,
  detailPathForType,
} from "./calendarEventTypes";
import type {
  CalendarEvent,
  CustomView,
  DayWithEvent,
  EventResource,
  MiniCalendarDate,
  Task,
} from "./calendarTypes";
import {
  calendarEntryKey,
  type CalendarEntryRecord,
} from "@/features/calendar/calendarEntry";

/** Extracted from the component of the same name. */
export function useCalendar() {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRTL = selectedLanguage === "ar";
  const router = useRouter();
  const { t } = useTranslation();
  const todayDate = useMemo(() => new Date(), []);

  const [view, setView] = useState<CustomView>("week");
  const [currentDate, setCurrentDate] = useState<Date>(todayDate);
  const [miniCalendarDate, setMiniCalendarDate] = useState<Date>(todayDate);
  // Ref for the calendar container so week view can scroll to today
  const calendarContainerRef = useRef<HTMLDivElement>(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);

  // Calculate range bounds for the query
  const monthStart = moment(miniCalendarDate).startOf("month").toDate();
  const monthEnd = moment(miniCalendarDate).endOf("month").toDate();
  const weekStart = moment(miniCalendarDate).startOf("week").toDate();
  const weekEnd = moment(miniCalendarDate).endOf("week").toDate();
  const dayStart = moment(miniCalendarDate).startOf("day").toDate();
  const dayEnd = moment(miniCalendarDate).endOf("day").toDate();

  // Map view to time_range for the query
  const timeRange = view === "year" ? "year" : view;

  const [showEventModal, setShowEventModal] = useState(false);
  const [modalEvents, setModalEvents] = useState<CalendarEvent[]>([]);
  const [modalDate, setModalDate] = useState<Date | null>(null);

  const rangeStart =
    timeRange === "year"
      ? undefined
      : moment(
          timeRange === "week"
            ? weekStart
            : timeRange === "month"
              ? monthStart
              : dayStart
        ).format("YYYY-MM-DD");

  const rangeEnd =
    timeRange === "year"
      ? undefined
      : moment(
          timeRange === "week"
            ? weekEnd
            : timeRange === "month"
              ? monthEnd
              : dayEnd
        ).format("YYYY-MM-DD");

  /*
   * The year view sends no explicit range — the API derives one from
   * `time_range: "year"`. It anchors that on the `date` param, and defaults to
   * `now()` when it is absent, so without this the year view always returned
   * the *current* year no matter which year the user had navigated to. The
   * other ranges send `start_date`/`end_date`, which the API prefers over this.
   */
  const anchorDate = moment(miniCalendarDate).format("YYYY-MM-DD");

  // Fetch calendar events with time_range param
  const { data, isLoading } = useQuery({
    queryKey: [
      "my-calendar",
      timeRange,
      debouncedSearch,
      rangeStart,
      rangeEnd,
      anchorDate,
    ],
    queryFn: () =>
      getCalendar({
        time_range: timeRange,
        search: debouncedSearch || undefined,
        start_date: rangeStart,
        end_date: rangeEnd,
        date: anchorDate,
      }),
  });


  // Scroll to today's date in week view when component loads or view changes
  useEffect(() => {
    const scrollToToday = () => {
      if (view !== "week" || !calendarContainerRef.current) return;

      // Get today's day of week (0 = Sunday, 6 = Saturday)
      const todayDayOfWeek = new Date().getDay();

      // Find all day columns in the calendar
      const dayColumns = calendarContainerRef.current.querySelectorAll(
        ".rbc-day-slot, .rbc-header"
      );

      // If we have columns and today is in the current week view
      if (dayColumns.length > 0 && todayDayOfWeek < dayColumns.length) {
        const todayColumn = dayColumns[todayDayOfWeek];
        if (!todayColumn) return;

        // Calculate the scroll position that centers today's column
        const containerWidth = calendarContainerRef.current.clientWidth;
        const columnLeft = todayColumn.getBoundingClientRect().left;
        const columnWidth = todayColumn.clientWidth;
        const containerScrollLeft = calendarContainerRef.current.scrollLeft;

        calendarContainerRef.current.scrollTo({
          left:
            containerScrollLeft +
            columnLeft -
            containerWidth / 2 +
            columnWidth / 2,
          behavior: "smooth",
        });
      }
    };

    // Short timeout to ensure the calendar is fully rendered
    const timeoutId = setTimeout(scrollToToday, 300);
    return () => clearTimeout(timeoutId);
  }, [view, currentDate]);

  // Use dynamic events from API
  const events: CalendarEvent[] = useMemo(() => {
    if (!data?.data) return [];

    const mapped: CalendarEvent[] = [];

    /*
     * Keyed on `type:id`, not `id`: volunteer opportunities, development
     * opportunities and events each have their own id sequence, so three
     * unrelated records can all be id 7.
     *
     * `CalendarController::deduplicateByStatusPriority()` already does this
     * server-side, preferring Organized over Registered over Saved. This pass
     * is therefore belt-and-braces rather than load-bearing — kept because it
     * is also what makes the first-wins ordering explicit here, and because the
     * endpoint merges three queries whose overlap is exactly what used to
     * render one card per relationship (BE-49 part 5).
     */
    const uniqueItems = new Map<string, CalendarEntryRecord>();
    data.data.forEach((event) => {
      const dedupeKey = calendarEntryKey(event);
      if (!uniqueItems.has(dedupeKey)) uniqueItems.set(dedupeKey, event);
    });

    uniqueItems.forEach((event) => {
      const apiType = event.type_en || event.type || "";
      let color = "#E0E0E0";
      if (apiType === "Volunteer" || apiType === "Opportunity")
        color = "#4DB6AC";
      if (apiType === "Learn" || LEARN_SERVE_TYPES.includes(apiType))
        color = "#CDDC39";
      if (apiType === "Event" || EVENT_TYPES.includes(apiType))
        color = "#5271FF";
      if (event.opportunity_status?.toLowerCase() === "completed")
        color = "#BDBDBD";

      const title =
        (isRTL ? event.title_ar : event.title_en) ||
        event.title_en ||
        event.title_ar ||
        "";
      const genericLabels = GENERIC_TYPE_LABELS[apiType];
      const displayType = isRTL
        ? event.type_ar || genericLabels?.ar || apiType
        : event.type_en || genericLabels?.en || apiType;
      const detailPath = detailPathForType(apiType);
      if (!detailPath) return;

      const resource: EventResource = {
        color,
        desc: `${t("COMMON.TYPE")}: ${displayType}`,
        type: displayType,
        detailPath,
        status: event.opportunity_status,
        id: event.id,
      };

      const startDate = moment(event.start_date, "YYYY-MM-DD");
      const endDate = moment(event.end_date, "YYYY-MM-DD");

      const hasTimes = Boolean(event.start_time && event.end_time);

      // For day/week view, create an event for each day in the range with the same time
      if (view === "day" || view === "week") {
        const current = startDate.clone();
        while (current.isSameOrBefore(endDate, "day")) {
          mapped.push({
            title,
            start: hasTimes
              ? moment(
                  `${current.format("YYYY-MM-DD")}T${event.start_time}`
                ).toDate()
              : current.clone().startOf("day").toDate(),
            end: hasTimes
              ? moment(
                  `${current.format("YYYY-MM-DD")}T${event.end_time}`
                ).toDate()
              : current.clone().add(1, "day").startOf("day").toDate(),
            allDay: !hasTimes,
            resource,
          });
          current.add(1, "day");
        }
      } else {
        // For month/year view, do not split
        mapped.push({
          title,
          start: hasTimes
            ? moment(`${event.start_date}T${event.start_time}`).toDate()
            : startDate.clone().startOf("day").toDate(),
          end: hasTimes
            ? moment(`${event.end_date}T${event.end_time}`).toDate()
            : endDate.clone().add(1, "day").startOf("day").toDate(),
          allDay: !hasTimes,
          resource,
        });
      }
    });

    return mapped;
  }, [data, isRTL, view, t]);

  // Handle event click for redirection
  const handleSelectEvent = (event: CalendarEvent) => {
    const { detailPath, id } = event.resource;

    if (!id) {
      console.error("Event ID is missing:", event);
      return;
    }

    router.push(`${detailPath}/${id}`);
  };

  // Days with events for the mini-calendar dots
  const daysWithEvents: DayWithEvent[] = useMemo(
    () =>
      events.reduce<DayWithEvent[]>((acc, event) => {
        const date = moment(event.start).format("YYYY-MM-DD");
        if (!acc.some((item) => item.date === date)) {
          acc.push({ date, color: event.resource.color });
        }
        return acc;
      }, []),
    [events]
  );

  // Generate dynamic tasks from events
  const upcomingTasks: Task[] = useMemo(() => {
    const today = moment();

    // Filter events for the next 7 days
    return events
      .filter((event) =>
        moment(event.start).isBetween(
          today,
          today.clone().add(7, "days"),
          "day",
          "[]"
        )
      )
      .sort((a, b) => a.start.getTime() - b.start.getTime())
      .map((event) => {
        const eventDate = moment(event.start);
        let category: string;

        if (eventDate.isSame(today, "day")) {
          category = "TODAY";
        } else if (eventDate.isSame(today.clone().add(1, "day"), "day")) {
          category = "TOMORROW";
        } else {
          category = eventDate.format("dddd").toUpperCase();
        }

        return {
          title: event.title,
          time: `${moment(event.start).format("h:mm A")} - ${moment(
            event.end
          ).format("h:mm A")}`,
          category,
          date: eventDate.format("M/D/YYYY"),
        };
      });
  }, [events]);

  // Group tasks by category
  const groupedTasks: Record<string, Task[]> = useMemo(
    () =>
      upcomingTasks.reduce<Record<string, Task[]>>((acc, task) => {
        if (!acc[task.category]) acc[task.category] = [];
        acc[task.category].push(task);
        return acc;
      }, {}),
    [upcomingTasks]
  );

  /*
   * The month grid is a pure function of the month being shown, today's date
   * and the event index — nothing else reads or writes it, and every write
   * replaced the whole array. It was `useState` + an effect that recomputed it
   * on exactly those three values, which is a `useMemo` with an extra render
   * per change and an empty first frame. Now it is the `useMemo`.
   */
  const miniCalendarDates: MiniCalendarDate[] = useMemo(() => {
    const date: Moment = moment(miniCalendarDate);
    const month = date.month();
    const year = date.year();

    const firstDay: Moment = moment(new Date(year, month, 1));
    const firstDayOfWeek = firstDay.day();
    const daysInMonth = date.daysInMonth();

    const calendarDays: MiniCalendarDate[] = [];

    // Add empty slots
    for (let i = 0; i < firstDayOfWeek; i++) {
      calendarDays.push({ day: null, date: null, isCurrentMonth: false });
    }

    // Add days of current month
    for (let i = 1; i <= daysInMonth; i++) {
      const dayDate: Moment = moment(new Date(year, month, i));
      calendarDays.push({
        day: i,
        date: dayDate.format("YYYY-MM-DD"),
        isCurrentMonth: true,
        isToday: dayDate.isSame(moment(currentDate), "day"),
        events: daysWithEvents.filter(
          (event) => event.date === dayDate.format("YYYY-MM-DD")
        ),
      });
    }

    // Complete the last week
    const remainingSlots = (7 - (calendarDays.length % 7)) % 7;
    for (let i = 1; i <= remainingSlots; i++) {
      calendarDays.push({
        day: i,
        date: moment(new Date(year, month + 1, i)).format("YYYY-MM-DD"),
        isCurrentMonth: false,
      });
    }

    return calendarDays;
  }, [miniCalendarDate, currentDate, daysWithEvents]);

  // Mini calendar navigation
  const navigateMiniCalendar = (direction: "prev" | "next") => {
    const date: Moment = moment(miniCalendarDate);
    const newDate =
      direction === "prev"
        ? date.subtract(1, "month").toDate()
        : date.add(1, "month").toDate();

    setMiniCalendarDate(newDate);
    // Move currentDate to the first day of the new month to trigger a fetch
    setCurrentDate(moment(newDate).startOf("month").toDate());
  };

  // Mini calendar day click handler
  const handleMiniCalendarDayClick = (dateObj: MiniCalendarDate) => {
    if (dateObj.date && dateObj.isCurrentMonth) {
      const newDate = moment(dateObj.date).toDate();
      setCurrentDate(newDate);
      setMiniCalendarDate(newDate);
    }
  };

  // Custom event style
  const eventStyleGetter = (
    event: CalendarEvent
  ): { style: React.CSSProperties } => {
    const backgroundColor = event.resource?.color ?? "#3174d7";
    const normalizedBgColor = backgroundColor.toUpperCase();

    let textColor = "#FFFFFF";
    let borderColor = backgroundColor;

    if (normalizedBgColor === "#D9EF61") {
      textColor = "#727272";
      borderColor = "#7E9017";
    } else if (normalizedBgColor === "#E0E0E0") {
      textColor = "#727272";
      borderColor = "#5B5B5B";
    } else if (normalizedBgColor === "#70B4C2") {
      borderColor = "#0A5F71";
    } else if (normalizedBgColor === "#5C6BC0") {
      borderColor = "#303F9F";
    } else if (normalizedBgColor === "#4DB6AC") {
      borderColor = "#00897B";
    } else if (normalizedBgColor === "#CDDC39") {
      textColor = "#827717";
      borderColor = "#9E9D24";
    }

    const baseStyle: React.CSSProperties = {
      backgroundColor,
      borderRadius: "4px",
      opacity: 1,
      color: textColor,
      border: "none",
      display: "flex",
      fontSize: "12px",
      boxSizing: "border-box",
      overflowY: "scroll",
      cursor: "pointer", // Indicate clickable events
      borderLeft: `3px solid ${borderColor}`,
    };

    if (view === "day") {
      return {
        style: {
          ...baseStyle,
          padding: "4px 8px",
          height: "auto",
          minHeight: "40px",
          width: "100%",
        },
      };
    }

    // Default styles for week and month views
    return {
      style: {
        ...baseStyle,
        padding: "8px",
        height: "auto",
        minHeight: "40px",
        width: "calc(100% - 0px)",
        marginLeft: isRTL ? "0" : "-1px",
        marginRight: isRTL ? "3px" : "0",
      },
    };
  };

  // Handle navigation in the big calendar
  const handleNavigate = (newDate: Date) => {
    setCurrentDate(newDate);
    setMiniCalendarDate(newDate);
  };

  // Go to today
  const goToToday = () => {
    const now = new Date();
    setCurrentDate(now);
    setMiniCalendarDate(now);
  };

  // Custom time slot formatter
  const formats = {
    timeGutterFormat: (date: Date, culture?: string): string =>
      localizer.format(date, "h A", culture),
    dayFormat: (date: Date, culture?: string): string =>
      localizer.format(date, "ddd", culture).toUpperCase(),
    dayHeaderFormat: (date: Date, culture?: string): string =>
      view === "day"
        ? localizer.format(date, "dddd, MMMM D", culture)
        : localizer.format(date, "ddd D", culture),
    dayRangeHeaderFormat: (
      { start, end }: { start: Date; end: Date },
      culture?: string
    ): string =>
      `${localizer.format(start, "MMMM", culture)} ${localizer
        .format(start, "D", culture)
        .padStart(2, "0")} - ${localizer
        .format(end, "D", culture)
        .padStart(2, "0")}, ${localizer.format(start, "YYYY", culture)}`,
    eventTimeRangeFormat: (
      { start, end }: { start: Date; end: Date },
      culture?: string
    ): string =>
      view === "day"
        ? `${localizer.format(start, "h:mm A", culture)} - ${localizer.format(
            end,
            "h:mm A",
            culture
          )}`
        : `${localizer.format(start, "h:mm A", culture)}`,
    selectRangeFormat: (
      { start, end }: { start: Date; end: Date },
      culture?: string
    ): string =>
      `${localizer.format(start, "h:mm A", culture)} - ${localizer.format(
        end,
        "h:mm A",
        culture
      )}`,
  };

  const toggleSidebar = () => setSidebarOpen((prev) => !prev);

  return {
    selectedLanguage,
    isRTL,
    router,
    todayDate,
    view,
    setView,
    currentDate,
    setCurrentDate,
    miniCalendarDate,
    setMiniCalendarDate,
    miniCalendarDates,
    calendarContainerRef,
    sidebarOpen,
    setSidebarOpen,
    searchQuery,
    setSearchQuery,
    debouncedSearch,
    monthStart,
    monthEnd,
    weekStart,
    weekEnd,
    dayStart,
    dayEnd,
    timeRange,
    showEventModal,
    setShowEventModal,
    modalEvents,
    setModalEvents,
    modalDate,
    setModalDate,
    rangeStart,
    rangeEnd,
    anchorDate,
    data,
    isLoading,
    events,
    handleSelectEvent,
    daysWithEvents,
    upcomingTasks,
    groupedTasks,
    navigateMiniCalendar,
    handleMiniCalendarDayClick,
    eventStyleGetter,
    handleNavigate,
    goToToday,
    formats,
    toggleSidebar,
  };
}
