"use client";
import * as React from "react";
import { HeroUIProvider } from "@heroui/system";
import { useRouter } from "next/navigation";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { ThemeProviderProps } from "next-themes/dist/types";
import { NextIntlClientProvider } from "next-intl";
import storedLanguage from "@/store/language-store";

export interface ProvidersProps {
  children: React.ReactNode;
  themeProps?: ThemeProviderProps;
}

export function Providers({ children, themeProps }: ProvidersProps) {
  const router = useRouter();
  const [localeNow, setLocaleNow] = React.useState<string>("id");
  const [messages, setMessages] = React.useState<any>(null);

  const locale = storedLanguage((state) => state.locale);

  React.useEffect(() => {
    if (locale) {
      setLocaleNow(locale);
    }
  }, [locale]);

  React.useEffect(() => {
    (async () => {
      const loadedMessages = (await import(`../messages/${locale}.json`))
        .default;
      setMessages(loadedMessages);
    })();
  }, [locale]);

  return (
    <NextIntlClientProvider locale={locale} messages={messages}>
      <HeroUIProvider navigate={router.push}>
        <NextThemesProvider {...themeProps}>{children}</NextThemesProvider>
      </HeroUIProvider>
    </NextIntlClientProvider>
  );
}
