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 (): Promise<void> => {
    setLoading(true);
    setError(null);

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

  useEffect(() => {
    void load();
  }, [load]);

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