"use client";

import React, { useState, useEffect } from "react";
import { timezones } from "@lifetracker/shared/utils/timezones";
import TimezoneSelect, { type ITimezone } from 'react-timezone-select'
import { useUpdateUserTimezone } from "@lifetracker/shared-react/hooks/timezones";
import { updateTimezoneCookie } from "@/lib/userLocalSettings/userLocalSettings";

export default function ChangeTimezone({ userTimezone }) {
    const [selectedTimezone, setSelectedTimezone] = useState<ITimezone>(userTimezone);
    const { mutate: updateUserTimezone, isPending } = useUpdateUserTimezone({
        onSuccess: (_data, { newTimezone }) => {
            updateTimezoneCookie(newTimezone);
            toast({
                description: "User DB Timezone updated!",
            });
        },
    });
    return (

        <TimezoneSelect
            value={selectedTimezone}
            onChange={(tz) => {
                setSelectedTimezone(tz);
                updateUserTimezone({ newTimezone: tz.value });
                window.dispatchEvent(new CustomEvent('timezoneUpdated', { detail: { timezone: tz.value } }));
            }}
            timezones={{
                ...timezones
            }}
        />
    );
}