import { createContext } from "preact";
import { useContext } from "preact/compat";
import { useEffect, useState } from "preact/hooks";
import { DateTime } from "luxon";
import { fetchUserInfo } from "../../api";
import { useQuery } from "react-query";

type TTimezoneContext = [string, (tz: string) => void];

const TimezoneContext = createContext(["UTC", () => {}] as TTimezoneContext);

export const TimezoneProvider = ({ children }) => {
    const { data } = useQuery({ ...fetchUserInfo() });

    const [timezone, setTimezone] = useState(DateTime.now().zoneName);

    useEffect(() => {
        setTimezone(
            data === undefined || data.preferences.use_browser_timezone
                ? DateTime.now().zoneName
                : data.preferences.timezone,
        );
    }, [data]);

    return (
        <TimezoneContext.Provider value={[timezone, setTimezone]}>
            {children}
        </TimezoneContext.Provider>
    );
};

export const useTimezone = () => useContext(TimezoneContext);
