import { createContext, useCallback, useContext, useMemo, useState } from "react";
import {
  DEFAULT_TIME_ZONE,
  TIME_ZONE_OPTIONS,
  formatMillis,
  getTimeZoneLabel,
  readStoredTimeZone,
  setActiveTimeZone,
  writeStoredTimeZone
} from "@/shared/utils/time.js";

const fallbackContext = {
  formatMillis: (value) => formatMillis(value, DEFAULT_TIME_ZONE),
  setTimeZone: () => {},
  timeZone: DEFAULT_TIME_ZONE,
  timeZoneLabel: getTimeZoneLabel(DEFAULT_TIME_ZONE),
  timeZoneOptions: TIME_ZONE_OPTIONS
};

const TimeZoneContext = createContext(fallbackContext);

export function TimeZoneProvider({ children }) {
  const [timeZone, setTimeZoneState] = useState(() => setActiveTimeZone(readStoredTimeZone()));

  const setTimeZone = useCallback((value) => {
    const normalized = setActiveTimeZone(value);
    writeStoredTimeZone(normalized);
    setTimeZoneState(normalized);
  }, []);

  const value = useMemo(
    () => ({
      formatMillis: (input) => formatMillis(input, timeZone),
      setTimeZone,
      timeZone,
      timeZoneLabel: getTimeZoneLabel(timeZone),
      timeZoneOptions: TIME_ZONE_OPTIONS
    }),
    [setTimeZone, timeZone]
  );

  return <TimeZoneContext.Provider value={value}>{children}</TimeZoneContext.Provider>;
}

export function useTimeZone() {
  return useContext(TimeZoneContext);
}
