import { formatDateToYYYYMMDD } from "@/lib/helpers";
import { type CreateTimeSlot } from "./createTimeSlotTypes";
import { parseDate } from "./timeSlotDateHelpers";

/**
 * What the slot form opens with.
 *
 * The fallback matters: a stored slot date can fall **outside** the
 * opportunity's window if the organiser has since shortened it. Opening the form
 * on that date would show a field that is invalid before it is touched and give
 * no hint why, so it falls back to the opportunity's own start instead.
 */
export function buildTimeSlotInitialValues({
  editTimeSlot,
  opportunityStartDate,
  opportunityEndDate,
  startDate,
}: {
  editTimeSlot?: CreateTimeSlot | null;
  opportunityStartDate: Date | null;
  opportunityEndDate: Date | null;
  startDate?: string;
}): { date: string; startTime: string; endTime: string; needed: string } {
  // Editing: fall back to the opportunity start when the stored date is out of range
  let initialDate: string;
  if (editTimeSlot) {
    // Same calendar-day parsing as the bounds, so a slot on the last day is in range.
    const editSlotDate = parseDate(editTimeSlot.date);
    if (
      editSlotDate &&
      opportunityStartDate &&
      opportunityEndDate &&
      editSlotDate >= opportunityStartDate &&
      editSlotDate <= opportunityEndDate
    ) {
      initialDate = formatDateToYYYYMMDD(editTimeSlot.date);
    } else {
      initialDate = editTimeSlot.opportunity_start_date || startDate || "";
    }
  } else {
    initialDate = startDate || "";
  }

  const initialValues = {
    date: initialDate,
    startTime: editTimeSlot ? editTimeSlot.start_time.slice(0, 5) : "",
    endTime:
      editTimeSlot && editTimeSlot.end_time
        ? editTimeSlot.end_time.slice(0, 5)
        : "",
    needed: editTimeSlot ? String(editTimeSlot.needed) : "",
  };
  return initialValues;
}
