'use client';

import { NextIntlClientProvider } from 'next-intl';
import { useRouter } from 'next/navigation';
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import Cookies from 'js-cookie';
import { useMemoizedFn } from 'ahooks';
import { useLayoutStore } from '@/stores';

type Locale = 'zh-CN' | 'en-US';
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) {
  Cookies.set('locale', locale, { expires: 365, path: '/' });
}

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

export function IntlProvider({ children }: IntlProviderProps) {
  const [locale, setLocaleState] = useState<Locale>('en-US');
  const [messages, setMessages] = useState<Record<string, any>>();
  const router = useRouter();

  const setHydrated = useLayoutStore((s) => s.setHydrated);
  useEffect(() => {
    setHydrated();
  }, [setHydrated]);

  const loadLocale = useMemoizedFn(async (locale: Locale) => {
    // 动态加载, 提升首屏加载速度
    const messages = await import(`@/i18n/${locale}.ts`);
    setMessages(messages.default);
  });

  useEffect(() => {
    const cookieLocale = getLocaleFromCookie();

    if (cookieLocale) {
      loadLocale(cookieLocale);
      setLocaleState(cookieLocale);
    }
  }, []);

  const setLocale = useMemoizedFn(async (newLocale: Locale) => {
    setLocaleState(newLocale);
    setLocaleToCookie(newLocale);
    await loadLocale(newLocale);
    router.refresh();
  });

  if (!messages) return null;

  return (
    <LocaleContext.Provider value={{ locale, setLocale }}>
      <NextIntlClientProvider
        locale={locale as any}
        messages={messages}
        timeZone={Intl.DateTimeFormat().resolvedOptions().timeZone}
      >
        {children}
      </NextIntlClientProvider>
    </LocaleContext.Provider>
  );
}
