"use client";

import type { LearnServeTimeSlotRecord } from "@/features/opportunities/opportunityRecord";
import { learnServeSlotsToDrafts } from "@/features/opportunities/learnServeSlotDraft";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import type { TimeSlot } from "@/features/shared";
import { useTimeSlotsStore } from "@/store/timeSlotsStore";

/**
 * The timings editor and the two dialogs around it.
 *
 * Slots are edited in a Zustand store rather than in Formik, because the editor
 * is a modal that has to survive being closed and reopened. That is also why
 * "has anything changed?" needs a snapshot: the store still holds the previous
 * session's edits, so the only way to know whether closing the modal would lose
 * work is to compare against what it held when it opened.
 */
export function useTimeSlotModals({
  opportunityId,
  refetchTimeSlots,
  savedSlots,
}: {
  opportunityId: number | null;
  refetchTimeSlots: () => void;
  /** The server's copy, used to restore slots the organizer discards. */
  /**
   * The server's copy of the schedule, straight off
   * `timeslots_display` — the API shape, not a draft. It is converted below
   * rather than spread into a draft directly: the API row has no `isSaved`
   * and can carry a null date.
   */
  savedSlots?: readonly LearnServeTimeSlotRecord[] | null;
}) {
  const { t } = useTranslation();
  const timeSlots = useTimeSlotsStore((state) => state.timeSlots);
  const setTimeSlots = useTimeSlotsStore((state) => state.setTimeSlots);
  const clearTimeSlots = useTimeSlotsStore((state) => state.clearTimeSlots);

  const [open, setOpen] = useState(false);
  const [opentime, setOpentime] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  /*
   * Derived, not stored: nothing but the removed effect set it, so it always
   * equalled `areTimeSlotsUnchanged`. That effect also skipped the update
   * while the modal was closed, which only froze a value nothing was
   * rendering.
   */
  const [initialTimeSlots, setInitialTimeSlots] = useState<TimeSlot[]>([]);

  const areTimeSlotsUnchanged = useMemo(() => {
    if (initialTimeSlots.length !== timeSlots.length) return false;

    return initialTimeSlots.every((initialSlot, index) => {
      const currentSlot = timeSlots[index];
      return (
        initialSlot.id === currentSlot.id &&
        initialSlot.date === currentSlot.date &&
        initialSlot.start_time === currentSlot.start_time &&
        initialSlot.end_time === currentSlot.end_time &&
        initialSlot.participants_needed === currentSlot.participants_needed &&
        initialSlot.isSaved === currentSlot.isSaved
      );
    });
  }, [initialTimeSlots, timeSlots]);

  const disableSaveButton = areTimeSlotsUnchanged;

  const handleCloseTimeModal = () => {
    setOpentime(false);
    if (opportunityId) {
      refetchTimeSlots();
    }
  };

  /**
   * Discarding unsaved edits: keep the slots the user actually saved, and
   * restore the rest from the server copy.
   */
  const handleConfirmAction = () => {
    const savedTimeSlots = timeSlots.filter((slot) => slot.isSaved === true);
    const combinedTimeSlots = [...savedTimeSlots];

    for (const displaySlot of learnServeSlotsToDrafts(savedSlots)) {
      if (!savedTimeSlots.some((savedSlot) => savedSlot.id === displaySlot.id)) {
        combinedTimeSlots.push(displaySlot);
      }
    }

    try {
      clearTimeSlots();
      setTimeSlots(combinedTimeSlots);
      toast.success(t("COMMON.TOAST.DELETE_TIME_SLOT_SUCCESS"));
    } catch (error) {
      console.error("Error performing action:", error);
      toast.error(t("COMMON.TOAST.DELETE_TIME_SLOT_FAILED"));
    } finally {
      setShowConfirmModal(false);
      setOpen(false);
    }
  };

  /** Closing with unsaved edits asks first; closing with none just closes. */
  const handleTimeSlotModalClose = () => {
    if (areTimeSlotsUnchanged) {
      setOpen(false);
    } else {
      setShowConfirmModal(true);
    }
  };

  return {
    open,
    setOpen,
    opentime,
    setOpentime,
    showConfirmModal,
    setShowConfirmModal,
    disableSaveButton,
    setInitialTimeSlots,
    handleCloseTimeModal,
    handleConfirmAction,
    handleTimeSlotModalClose,
  };
}
