"use client";

import { useMemo, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { registerForLearnServeOpportunity } from "@/features/opportunities/services/learnServe";
import { getConsultationTimeSlots, timeSlotItems } from "@/features/opportunities/services/registrations";
import { type ConsultationTimeSlot } from "./consultationTypes";

/**
 * A consultation opportunity's bookable slots, grouped by day.
 *
 * The earliest day is preselected so the picker opens on something rather than
 * an empty panel — and only when nothing is selected yet, so a later refetch
 * cannot pull the user off the day they chose.
 */
export function useConsultationSlots(opportunityId: string) {
  /*
   * The state holds the reader's *explicit* choice; `null` means "has not
   * picked yet", not "nothing is selected". The exposed `selectedDate` falls
   * back to the earliest day, so the preselection is a derivation rather than
   * an effect that wrote it one render after the slots arrived — the picker no
   * longer renders an empty panel for that frame.
   *
   * The "only when nothing is selected yet" rule still holds, and more
   * strictly: a refetch cannot move the reader because `chosenDate`, once set,
   * always wins. `earliestDate` is `""` when there are no days, and
   * `ConsultationSlotGrid` returns null on a falsy date exactly as it did for
   * `null`, so the empty case is unchanged.
   */
  const [chosenDate, setSelectedDate] = useState<string | null>(null);

  const timeSlotQuery = useQuery({
    queryKey: ["consultation-time-slots", opportunityId],
    queryFn: () => getConsultationTimeSlots(opportunityId),
    enabled: Boolean(opportunityId),
  });

  const registerMutation = useMutation({
    mutationFn: registerForLearnServeOpportunity,
  });

  const timeSlots: ConsultationTimeSlot[] = useMemo(
    // `data` is `{ items, remaining_participants }`; reading it as the array
    // made every slot list look empty.
    () => timeSlotItems(timeSlotQuery.data?.data),
    [timeSlotQuery.data]
  );

  const timeSlotsByDate = useMemo(
    () =>
      timeSlots.reduce<Record<string, ConsultationTimeSlot[]>>((acc, slot) => {
        /* A slot with no date is skipped rather than grouped. `date` is
           nullable on the resource, and `acc[null]` would have created a
           literal `"null"` key — i.e. a day tab labelled "null" that the
           reader could select and that holds slots belonging to no date. */
        if (!slot.date) return acc;
        (acc[slot.date] ||= []).push(slot);
        return acc;
      }, {}),
    [timeSlots]
  );

  const dates = useMemo(() => Object.keys(timeSlotsByDate), [timeSlotsByDate]);

  const earliestDate = useMemo(() => {
    if (dates.length === 0) return "";
    return [...dates].sort(
      (a, b) => new Date(a).getTime() - new Date(b).getTime()
    )[0];
  }, [dates]);

  const selectedDate: string | null = chosenDate ?? (earliestDate || null);

  return {
    earliestDate,
    isError: timeSlotQuery.isError,
    timeSlots,
    selectedDate,
    setSelectedDate,
    timeSlotsByDate,
    dates,
    isLoading: timeSlotQuery.isLoading,
    registerMutation,
  };
}
