"use client";

import { formatForDisplay } from "@/features/opportunities/components/scheduleDateValues";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import { useTimeSlotsStore } from "@/store/timeSlotsStore";
import { TimeSlot } from "@/features/shared";
import { useWindowWidth } from "@/hooks/useWindowWidth";

import { useTranslation } from "react-i18next";
import { type EventTimeSlotModalProps } from "./EventTimeSlotModal";

/**
 * One row of the event's time-slot table: a saved slot, reduced to what the
 * table shows.
 *
 * Not the payload shape — `date` has already been grouped into the key and
 * the two times joined into one display string, so this is the view model.
 */
export interface EventTimeSlotDisplayRow {
  id: number;
  /** `"HH:mm - HH:mm"`, already formatted. */
  time: string;
  needed: number;
  /** The draft row this was built from, for the edit modal. */
  rawSlot: TimeSlot;
}

export const formatTime = (timeString: string | null): string => {
  if (!timeString) return "N/A";
  return timeString.slice(0, 5); // "HH:mm"
};

/**
 * The event time-slot editor's state: the slot list from the store, the
 * add/edit/delete flow and the confirm-dialog bookkeeping.
 */
export function useEventTimeSlots({
  startDate,
  endDate,
  startTime,
  endTime,
  setOpen,
}: EventTimeSlotModalProps) {
  const { t, i18n } = useTranslation();
  const [opentime, setOpentime] = useState(false);
  const [editingTimeSlot, setEditingTimeSlot] = useState<TimeSlot | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [confirmAction, setConfirmAction] = useState<"delete" | "clear" | null>(
    null
  );
  const [slotIdToDelete, setSlotIdToDelete] = useState<number | null>(null);
  const windowWidth = useWindowWidth();


  // Draft slots live in the shared store until the parent form is submitted
  const timeSlots = useTimeSlotsStore((s) => s.timeSlots);
  const deleteTimeSlot = useTimeSlotsStore((s) => s.deleteTimeSlot);
  const clearTimeSlots = useTimeSlotsStore((s) => s.clearTimeSlots);
  const updateTimeSlot = useTimeSlotsStore((s) => s.updateTimeSlot);

  // Use props directly for event details
  const oppStartDate = startDate || "";
  const oppEndDate = endDate || "";
  const oppStartTime = startTime || "";
  const oppEndTime = endTime || "";

  const handleTimeSlotCreated = () => {
    setOpentime(false);
    setEditingTimeSlot(null);
  };

  const handleEditClick = (slotId: number) => {
    const slot = timeSlots.find((s) => s.id === slotId);
    if (slot) {
      setEditingTimeSlot(slot);
      setOpentime(true);
    }
  };

  const handleDeleteClick = (slotId: number) => {
    setSlotIdToDelete(slotId);
    setConfirmAction("delete");
    setShowConfirmModal(true);
  };

  const handleConfirmAction = () => {
    try {
      if (confirmAction === "delete" && slotIdToDelete !== null) {
        deleteTimeSlot(slotIdToDelete);
        toast.success(t("COMMON.TOAST.DELETE_TIME_SLOT_SUCCESS"));
      } else if (confirmAction === "clear") {
        clearTimeSlots();
        toast.success(t("COMMON.TOAST.CLEAR_TIME_SLOTS_SUCCESS"));
      }
    } catch (error) {
      console.error("Error performing action:", error);
      toast.error(
        confirmAction === "delete"
          ? t("COMMON.TOAST.DELETE_TIME_SLOT_FAILED")
          : t("COMMON.TOAST.CLEAR_TIME_SLOTS_FAILED")
      );
    } finally {
      setShowConfirmModal(false);
      setConfirmAction(null);
      setSlotIdToDelete(null);
    }
  };

  const groupedTimeSlots = useMemo(() => {
    if (!timeSlots.length) return {};

    /* The accumulator is typed rather than `any`: it is a date-keyed bucket
       of display rows, and the rows are what `EventTimeSlotTable` renders. */
    return timeSlots.reduce<Record<string, EventTimeSlotDisplayRow[]>>((acc, slot) => {
      // `new Date("YYYY-MM-DD")` is UTC midnight: the browser's zone and locale
      // showed the previous day west of UTC, in the OS language.
      const date = formatForDisplay(slot.date, i18n.language);
      if (!acc[date]) acc[date] = [];
      acc[date].push({
        id: slot.id,
        time: `${formatTime(slot.start_time)} - ${formatTime(slot.end_time)}`,
        needed: slot.participants_needed,
        rawSlot: slot,
      });
      return acc;
    }, {});
  }, [timeSlots, i18n.language]);

  const isLoading = !oppStartDate || !oppEndDate;

  const handleSaveTimeSlots = () => {
    timeSlots.forEach((slot) => updateTimeSlot({ ...slot, isSaved: true }));
    setOpen(false);
    toast.success(t("COMMON.TOAST.CREATE_TIME_SLOT_SUCCESS"));
  };

  return {
    opentime,
    setOpentime,
    editingTimeSlot,
    setEditingTimeSlot,
    showConfirmModal,
    setShowConfirmModal,
    confirmAction,
    setConfirmAction,
    slotIdToDelete,
    setSlotIdToDelete,
    windowWidth,
    timeSlots,
    deleteTimeSlot,
    clearTimeSlots,
    updateTimeSlot,
    oppStartDate,
    oppEndDate,
    oppStartTime,
    oppEndTime,
    handleTimeSlotCreated,
    handleEditClick,
    handleDeleteClick,
    handleConfirmAction,
    groupedTimeSlots,
    isLoading,
    handleSaveTimeSlots,
  };
}
