import { createContext, useContext, type ReactNode } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import toast from 'react-hot-toast';

interface TimezoneContextValue {
  timezone: string;
  isLoading: boolean;
  setTimezone: (tz: string) => void;
}

const TimezoneContext = createContext<TimezoneContextValue>({
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  isLoading: false,
  setTimezone: () => {},
});

export function TimezoneProvider({ children }: { children: ReactNode }) {
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery<{ timezone: string }>({
    queryKey: ['settings', 'timezone'],
    queryFn: async () => {
      const { data } = await api.get('/settings/timezone');
      return data;
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  const mutation = useMutation({
    mutationFn: async (timezone: string) => {
      const { data } = await api.patch('/settings/timezone', { timezone });
      return data;
    },
    onSuccess: (data) => {
      queryClient.setQueryData(['settings', 'timezone'], data);
      toast.success('Timezone updated');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.message || 'Failed to update timezone');
    },
  });

  const timezone = data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;

  return (
    <TimezoneContext.Provider
      value={{
        timezone,
        isLoading,
        setTimezone: (tz: string) => mutation.mutate(tz),
      }}
    >
      {children}
    </TimezoneContext.Provider>
  );
}

/**
 * Get the app-wide timezone string
 */
export function useTimezone(): string {
  return useContext(TimezoneContext).timezone;
}

/**
 * Get the full timezone context (timezone, isLoading, setTimezone)
 */
export function useTimezoneContext(): TimezoneContextValue {
  return useContext(TimezoneContext);
}
