/**
 * React hook for schedule calendar day availability.
 *
 * Calls `getScheduleCalendarDays` on param change, manages loading/days state.
 *
 * @module
 */

import { useState, useEffect, useRef } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { getScheduleCalendarDays } from "../api.js";
import type { IScheduleCalendarParams } from "../types.js";

export interface UseScheduleCalendarResult {
  days: string[];
  loading: boolean;
}

/**
 * Hook for the calendar strip. Fetches available schedule days for the
 * given route context.
 */
export function useScheduleCalendar(
  params: IScheduleCalendarParams,
): UseScheduleCalendarResult {
  const client = useApiClient();
  const [days, setDays] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  const paramsRef = useRef(params);
  paramsRef.current = params;

  useEffect(() => {
    let cancelled = false;
    setLoading(true);

    getScheduleCalendarDays(client, paramsRef.current)
      .then((result) => {
        if (!cancelled) {
          setDays(result);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setDays([]);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [
    client,
    params.date,
    params.departure,
    params.arrival,
    params.connections,
  ]);

  return { days, loading };
}
