import fetchData from "@/api/fetch-data";
import ProductLayoutClient from "@/app/ui/products/ProductLayoutClient";
import SectionHeader from "@/app/ui/shared/SectionHeader";
import {
  dehydrate,
  HydrationBoundary,
  QueryClient,
} from "@tanstack/react-query";
import { getLocale, getTranslations } from "next-intl/server";
import FilterSheet from "../../../ui/products/FilterSheet";
import AlertWarning from "../../../ui/shared/AlertWarning";
import CustomBreadcrumb from "../../../ui/shared/CustomBreadcrumb";

const Page = async ({ params }) => {
  const queryClient = new QueryClient();
  const { id } = params;
  // Get locale and token
  const locale = await getLocale();
  const t = await getTranslations("filter");

  const res = await queryClient.fetchQuery({
    queryKey: [locale, `/categories/${id}`],
    queryFn: () =>
      fetchData({
        endPoint: `/categories/${id}`,
        locale,
      }),
  });

  //START Default Fetched data

  if (res.error)
    return <AlertWarning text={res.message || "توجد صيانه في الموقع حاليا "} />;

  let { data, message, error } = res;

  if (data == null) return <AlertWarning text={message} />;
  if (!error && data?.products?.data?.length == 0)
    return <AlertWarning text={message} />;

  const subCategories = res?.data?.category?.sub_categories || [];
  //END Default Fetched data
  return (
    <div>
      {/* breadCrumb */}
      <CustomBreadcrumb title={t("products")} subs={true} number={2} />
      {/* page layout */}

      <HydrationBoundary state={dehydrate(queryClient)}>
        <div className="container my-8 space-y-6">
          {/* header */}
          <div className="grid grid-cols-12 gap-y-6">
            <div className="lg:col-span-2 md:col-span-4 md:block hidden">
              <SectionHeader
                title={t("filter")}
                marker={t("search")}
                withLink={false}
              />
            </div>
            <div className="lg:col-span-10 md:col-span-8 col-span-12">
              <SectionHeader
                title={t("content")}
                marker={t("search")}
                withLink={false}
              />
            </div>
            <div className="col-span-12 block md:hidden">
              <FilterSheet filters={data?.filters} />
            </div>
          </div>
          {/* layout */}
          <ProductLayoutClient data={data} subCategories={subCategories} />
        </div>
      </HydrationBoundary>
    </div>
  );
};

export default Page;
