import fetchData from "@/api/fetch-data";
import Blogs from "@/app/ui/home/Blogs";
import SideFetching from "@/app/ui/home/sideFetching/SideFetching";
import MainSliderRedesignThree from "@/app/ui/shared/MainSectionRedesignThree/MainSliderRedesignThree";
import AlertWarning from "./ui/shared/AlertWarning";
import MainFetchingRedesignTwo from "./ui/shared/MainFetchingRedesignTwo/MainFetchingRedesignTwo";
import Auctions from "./ui/home/Auctions";
import { getLocale } from "next-intl/server";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { getQueryClient } from "./get-query-client";
import { Suspense } from "react";
import { Loader2 } from "lucide-react";
import getUserProfile from "@/api/user/getUserProfile";

export default async function Home() {
  const main = [];
  const side = [];
  let slider = [];
  const l = await getLocale();
  const queryClient = getQueryClient();

  // prefetch auctions
  queryClient.prefetchQuery({
    queryKey: [
      `/auctions?page=1&random=true&limit=${process.env.NEXT_PUBLIC_NUMBER_OF_AUCTIONS_AT_HOME_PAGE}`,
      l,
    ], // Include page in query key for proper caching
    queryFn: () =>
      fetchData({
        endPoint: `/auctions?page=1&random=true&limit=${process.env.NEXT_PUBLIC_NUMBER_OF_AUCTIONS_AT_HOME_PAGE}`,
      }),
  });

  // prefetch user
  queryClient.prefetchQuery({
    queryKey: ["/user/get/profile"],
    queryFn: () => getUserProfile(),
  });

  const response = await fetchData({ endPoint: "/sections" });
  if (response.error) {
    return <AlertWarning text={response.message} />;
  }

  const sections = Object.keys(response)
    .filter((key) => !isNaN(key))
    .map((key) => response[key]);

  for (let i = 0; i < sections.length; i++) {
    if (sections[i].display_in === "main_body") {
      main.push(sections[i]);
    } else {
      side.push(sections[i]);
    }
  }

  // sorted main sections with dispaly-order
  main.sort((a, b) => a.display_order - b.display_order);
  // sorted side sections with dispaly-order
  side.sort((a, b) => a.display_order - b.display_order);

  // fetch data to slider
  const responseSlider = await fetchData({ endPoint: "/sliders" });
  if (responseSlider.status == "success") {
    slider = responseSlider.data;
  }

  return (
    //redesign three
    <main>
      <div className="space-y-8 my-8">
        <div className="container grid grid-cols-12 gap-6">
          <div
            className={`${
              side.length > 0
                ? "col-span-12 lg:col-span-8 xl:col-span-9"
                : "col-span-12"
            } `}
          >
            <MainSliderRedesignThree sliderArray={slider} />
            <Blogs />
            <MainFetchingRedesignTwo
              mainArray={main}
              styles="sm:basis-1/2 md:basis-1/3 lg:basis-1/2 xl:basis-1/3 2xl:basis-1/4"
              iconColor="hover:text-main"
            />
          </div>
          <div
            className={`${
              side.length > 0
                ? "col-span-12 lg:col-span-4 xl:col-span-3"
                : "hidden"
            } `}
          >
            <SideFetching sideArray={side} />
            <HydrationBoundary state={dehydrate(queryClient)}>
              <Suspense
                fallback={
                  <Loader2 className="animate-spin w-fit mx-auto mt-10" />
                }
              >
                <Auctions />
              </Suspense>
            </HydrationBoundary>
          </div>
        </div>
      </div>
    </main>
  );
}
