import Category from "@/components/category/Category";
import Product from "@/components/product/Product";
import { notFound } from "next/navigation";
import axios from "@/lib/axios";
import { redirect } from "next/navigation";
import BreadcrumbCustom from "@/components/constantElements/BreadcrumbCustom";
import styles from "../../../assets/css/category/MainCategory.module.css";
import QuickAccess from "@/layouts/QuickAccess";
import SideBar from "../../../components/category/SideBar";
import Paragraph from "@/components/special-box/Paragraph";
import Accordions from "@/components/Accordions";
import VideoCustom from "@/components/constantElements/VideoCustom";
import VideoBox from "@/components/VideoBox";
import CardsCarousel from "@/components/constantElements/CardsCarousel";
import ContentImageBox from "@/components/ContentImageBox";
import ProgressCustom from "@/components/constantElements/ProgressCustom";
import BannerCarousel from "@/components/constantElements/BannerCarousel";
import BrandsCarousel from "@/components/constantElements/BrandsCarousel";
import { data } from "autoprefixer";

const frontUrl = process.env.NEXT_PUBLIC_FRONTEND_URL;
const backendUrlImage = process.env.NEXT_PUBLIC_BACKEND_URL_IMAGE;
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL;

export async function generateMetadata({ params, searchParams }) {
  let video = false;
  async function pageApi(route) {
    const pageData = await axios
      .get(route)
      .then((res) => {
        return res;
      })
      .catch((error) => {
        if (error.response.status == "301" || error.response.status == "302") {
          if (
            error.response.data.type == "error" &&
            error.response.data.message == "redirect" &&
            error.response.data.redirect
          ) {
            redirect(error.response.data.redirect);
          } else {
            redirect(notFound());
          }
        } else {
          redirect(notFound());
        }
      });

    return pageData;
  }
  const slug = params.handler.join("/");
  const dataFetch = await pageApi(
    searchParams ? `api/${slug}?page=${searchParams.page}` : `api/${slug}`
  );

  if (dataFetch.data.type == "category") {
    dataFetch.data.category.special_box.map((e) => {
      if (e.content_type == "video") {
        video = true;
      }
    });

    if (dataFetch.data.products && !Array.isArray(dataFetch.data.products)) {
      dataFetch.data.products.data.map((e) => {
        if (e && e.video) {
          video = true;
        }
      });
    }


    const next = dataFetch.data.products && dataFetch.data.products.next_page_url && dataFetch.data.products.next_page_url.replace(`${backendUrl}/api/` , frontUrl)
    const prev = dataFetch.data.products && dataFetch.data.products.prev_page_url && dataFetch.data.products.prev_page_url.replace(`${backendUrl}/api/` , frontUrl)
    

    return {
      title: dataFetch.data.category.title,
      description: dataFetch.data.category.description,
      keywords: dataFetch.data.category.keywords,
      openGraph: {
        title: dataFetch.data.category.title,
        description: dataFetch.data.category.description,
        keywords: dataFetch.data.category.keywords,
      },
      alternates: {
        canonical: `${frontUrl}${dataFetch.data.category.slug}`,
      },
      robots: {
        index: dataFetch.data.category.index_status == 0 ? false : true,
        follow: dataFetch.data.category.index_status == 0 ? false : true,
      },

      ...(video
        ? dataFetch.data.products
          ? dataFetch.data.products.next_page_url &&
            dataFetch.data.products.prev_page_url
            ? {
                icons: {
                  other: [
                    {
                      rel: "next",
                      url: `${next}`,
                    },
                    {
                      rel: "prev",
                      url: `${prev}`,
                    },
                    {
                      rel: "preconnect",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "dns-prefetch",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "preconnect",
                      url: backendUrl,
                    },
                  ],
                },
              }
            : dataFetch.data.products.prev_page_url &&
              !dataFetch.data.products.next_page_url
            ? {
                icons: {
                  other: [
                    {
                      rel: "prev",
                      url: `${prev}`,
                    },
                    {
                      rel: "preconnect",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "dns-prefetch",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "preconnect",
                      url: backendUrl,
                    },
                  ],
                },
              }
            : dataFetch.data.products.next_page_url &&
              !dataFetch.data.products.prev_page_url
            ? {
                icons: {
                  other: [
                    {
                      rel: "next",
                      url: `${next}`,
                    },
                    {
                      rel: "preconnect",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "dns-prefetch",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "preconnect",
                      url: backendUrl,
                    },
                  ],
                },
              }
            : {
                icons: {
                  other: [
                    {
                      rel: "preconnect",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "dns-prefetch",
                      url: "https://upload.vidbeen.ir",
                    },
                    {
                      rel: "preconnect",
                      url: backendUrl,
                    },
                  ],
                },
              }
          : {
              icons: {
                other: [
                  {
                    rel: "preconnect",
                    url: "https://upload.vidbeen.ir",
                  },
                  {
                    rel: "dns-prefetch",
                    url: "https://upload.vidbeen.ir",
                  },
                  {
                    rel: "preconnect",
                    url: backendUrl,
                  },
                ],
              },
            }
        : dataFetch.data.products
        ? dataFetch.data.products.next_page_url &&
          dataFetch.data.products.prev_page_url
          ? {
              icons: {
                other: [
                  {
                    rel: "next",
                    url: `${next}`,
                  },
                  {
                    rel: "prev",
                    url: `${prev}`,
                  },
                  {
                    rel: "preconnect",
                    url: backendUrl,
                  },
                ],
              },
            }
          : dataFetch.data.products.prev_page_url &&
            !dataFetch.data.products.next_page_url
          ? {
              icons: {
                other: [
                  {
                    rel: "prev",
                    url: `${prev}`,
                  },
                  {
                    rel: "preconnect",
                    url: backendUrl,
                  },
                ],
              },
            }
          : dataFetch.data.products.next_page_url &&
            !dataFetch.data.products.prev_page_url
          ? {
              icons: {
                other: [
                  {
                    rel: "next",
                    url: `${next}`,
                  },
                  {
                    rel: "preconnect",
                    url: backendUrl,
                  },
                ],
              },
            }
          : {
              icons: {
                other: [
                  {
                    rel: "preconnect",
                    url: backendUrl,
                  },
                ],
              },
            }
        : null),
    };
  } else {
    return {
      title: dataFetch.data.products.title,
      description: dataFetch.data.products.description,
      keywords: dataFetch.data.products.keywords,
      openGraph: {
        title: dataFetch.data.products.title,
        description: dataFetch.data.products.description,
        images: `${backendUrlImage}${dataFetch.data.products.image.indexArray.original}`,
      },
      alternates: {
        canonical: `${frontUrl}${dataFetch.data.products.category.slug}/${dataFetch.data.products.slug}`,
      },
      robots: {
        index: dataFetch.data.products.index_status == 0 ? false : true,
        follow: dataFetch.data.products.index_status == 0 ? false : true,
      },
      icons: {
        other: [
          {
            rel: "preconnect",
            url: backendUrl,
          },
        ],
      },

      ...(dataFetch.data.products.video_path ||
      (dataFetch.data.products.active_video_galleries.length > 0 &&
        dataFetch.data.products.active_video_galleries[0].video_path)
        ? {
            icons: {
              other: [
                {
                  rel: "preconnect",
                  url: "https://upload.vidbeen.ir",
                },
                {
                  rel: "dns-prefetch",
                  url: "https://upload.vidbeen.ir",
                },
                {
                  rel: "preconnect",
                  url: backendUrl,
                },
              ],
            },
          }
        : null),

      other: {
        product_id: dataFetch.data.products.id,
        product_name: dataFetch.data.products.name,
        product_price: dataFetch.data.products.price,
        product_old_price: dataFetch.data.products.price,
        availability:
          dataFetch.data.products.marketable == 0 ? "instock" : "outofstock",
        guarantee: dataFetch.data.products.guarantee,
      },
    };
  }
}

export default async function Page({ params, searchParams }) {
  
  let values = Object.values(searchParams)
  values.splice(values.length - 1 , 1)


  async function pageApi(route) {
    const pageData = await axios
      .get(route)
      .then((res) => {
        return res;
      })
      .catch((error) => {
        if (error.response.status == "301" || error.response.status == "302") {
          if (
            error.response.data.type == "error" &&
            error.response.data.message == "redirect" &&
            error.response.data.redirect
          ) {
            redirect(error.response.data.redirect);
          } else {
            redirect(notFound());
          }
        } else {
          redirect(notFound());
        }
      });

    return pageData;
  }
  const newSearchParams = new URLSearchParams(searchParams).toString();

  const slug = params.handler.join("/");
  const pageData = await pageApi(
    searchParams ? `api/${slug}?${newSearchParams}` : `api/${slug}`
  );

  const category = await pageData.data.category;
  const product = await pageData.data.products;

  const jsonId = await category.body

  return pageData.data.type == "category" ? (
    <>
      <BreadcrumbCustom
        categorySlug={category.slug}
        breadcrumb={category.bread_crumb}
        parentId={category.parent_id}
        categoryName={category.main_name}
        structure={category.json_bread_crumb}
      />
      {/* <Title position="head" titleValue={category.main_name} /> */}
      <h1 className={styles.title}>{category.main_name}</h1>
      <Category
        testValue = {values}
        apiData={pageData.data}
        pages={(await searchParams).page}
        scrollTo={newSearchParams}
        currentSlug={slug}
      />
      
      <QuickAccess />
    </>
  ) : (
    <>
      <BreadcrumbCustom
        breadcrumb={product.bread_crumb}
        parentId={product.parent_id}
        type="product"
        categoryName={product.name}
        categorySlug={product.slug}
        structure={product.json_bread_crumb}
      />
      <Product
        apiData={product}
        type={pageData.data.type}
        // user={dataUser}
      />
    </>
  );
}
