"use client";

import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "@/lib/query-client";
import SettingsProvider from "@/context/settings/settings";
import { Country, Currency, Language } from "@/types/global";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { PropsWithChildren, useEffect, useState } from "react";
import "@/utils/dayjs";
import useUserStore from "@/global-store/user";
import useAddressStore from "@/global-store/address";
import useSettingsStore from "@/global-store/settings";
import useCartStore from "@/global-store/cart";
import useLikeStore from "@/global-store/like";
import useCompareStore from "@/global-store/compare";
import useSearchHistoryStore from "@/global-store/search-history";

interface ProviderProps extends PropsWithChildren {
  defaultCurrency?: Currency;
  defaultLanguage?: Language;
  settings?: Record<string, string>;
  currencies?: Currency[];
  defaultCountry?: Country;
}

const Providers = ({
  children,
  defaultCurrency,
  defaultLanguage,
  settings,
  currencies,
  defaultCountry,
}: ProviderProps) => {
  const [client] = useState(() => queryClient);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    useUserStore.persist.rehydrate();
    useAddressStore.persist.rehydrate();
    useSettingsStore.persist.rehydrate();
    useCartStore.persist.rehydrate();
    useLikeStore.persist.rehydrate();
    useCompareStore.persist.rehydrate();
    useSearchHistoryStore.persist.rehydrate();
  }, []);

  return (
    <QueryClientProvider client={client}>
      <SettingsProvider
        currencies={currencies}
        defaultLanguage={defaultLanguage}
        defaultCurrency={defaultCurrency}
        settings={settings}
        defaultCountry={defaultCountry}
      >
        {children}
      </SettingsProvider>
      {mounted && process.env.NODE_ENV === "development" ? <ReactQueryDevtools /> : null}
    </QueryClientProvider>
  );
};

export default Providers;
