'use client';

import { NextIntlClientProvider } from 'next-intl';
import {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
  useCallback,
} from 'react';
import Cookies from 'js-cookie';
import zhMessages from '@/locales/zh';
import enMessages from '@/locales/en';

type Locale = 'zh' | 'en';

const messages: Record<Locale, any> = {
  zh: zhMessages,
  en: enMessages,
};

interface LocaleContextType {
  locale: Locale;
  setLocale: (locale: Locale) => void;
}

const LocaleContext = createContext<LocaleContextType | undefined>(undefined);

export function useLocale() {
  const context = useContext(LocaleContext);
  if (!context) {
    throw new Error('useLocale must be used within IntlProvider');
  }
  return context;
}

interface IntlProviderProps {
  children: ReactNode;
}

function setLocaleToCookie(locale: Locale) {
  if (typeof window === 'undefined') return;
  Cookies.set('locale', locale, { expires: 365, path: '/' });
}

function getLocaleFromCookie(): Locale {
  if (typeof window === 'undefined') return 'en';
  const cookieLocale = Cookies.get('locale') as Locale | undefined;
  if (cookieLocale && (cookieLocale === 'zh' || cookieLocale === 'en')) {
    return cookieLocale;
  }
  return 'en';
}

export function IntlProvider({ children }: IntlProviderProps) {
  const [locale, setLocaleState] = useState<Locale>('en');

  useEffect(() => {
    const cookieLocale = getLocaleFromCookie();
    if (cookieLocale) {
      setLocaleState(cookieLocale);
    }
  }, []);

  const setLocale = useCallback((newLocale: Locale) => {
    setLocaleState(newLocale);
    setLocaleToCookie(newLocale);
  }, []);

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      <NextIntlClientProvider
        locale={locale as any}
        messages={messages[locale]}
        timeZone="Asia/Shanghai"
      >
        {children}
      </NextIntlClientProvider>
    </LocaleContext.Provider>
  );
}
