import { useCallback, useEffect, useState } from "react";
import { fetchTimezone } from "../api/setup";
import { handleFetchError } from "../utils/fetchError";

export interface UseTimezoneDataResult {
  timezone: string;
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
}

export function useTimezoneData(): UseTimezoneDataResult {
  const [timezone, setTimezone] = useState<string>("UTC");
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async (signal?: AbortSignal): Promise<void> => {
    setLoading(true);
    setError(null);

    try {
      const resp = await fetchTimezone(signal);
      if (signal?.aborted) return;
      setTimezone(resp.timezone);
    } catch (err: unknown) {
      if (signal?.aborted) return;
      handleFetchError(err, setError, "Failed to fetch timezone");
      setTimezone("UTC");
    } finally {
      if (!signal?.aborted) {
        setLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    const controller = new AbortController();
    void load(controller.signal);
    return (): void => {
      controller.abort();
    };
  }, [load]);

  return {
    timezone,
    loading,
    error,
    refresh: load,
  };
}
