/**
 * React hook for fetching and updating the blocklist import schedule.
 */

import { useCallback, useEffect, useState } from "react";
import { fetchSchedule, updateSchedule } from "../api/blocklist";
import { handleFetchError } from "../utils/fetchError";
import type { ScheduleConfig, ScheduleInfo } from "../types/blocklist";

export interface UseScheduleReturn {
  info: ScheduleInfo | null;
  loading: boolean;
  error: string | null;
  saveSchedule: (config: ScheduleConfig) => Promise<void>;
}

/**
 * Fetch and update the blocklist import schedule.
 */
export function useSchedule(): UseScheduleReturn {
  const [info, setInfo] = useState<ScheduleInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);
    setError(null);

    fetchSchedule(controller.signal)
      .then((data) => {
        if (controller.signal.aborted) return;
        setInfo(data);
      })
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        handleFetchError(err, setError, "Failed to load schedule");
      })
      .finally(() => {
        if (controller.signal.aborted) return;
        setLoading(false);
      });

    return (): void => {
      controller.abort();
    };
  }, []);

  const saveSchedule = useCallback(async (config: ScheduleConfig): Promise<void> => {
    const updated = await updateSchedule(config);
    setInfo(updated);
  }, []);

  return { info, loading, error, saveSchedule };
}
