import React from "react";
import BreadcrumbCustom from "@/components/constantElements/BreadcrumbCustom";
import axios from "@/lib/axios";
import { redirect, notFound } from "next/navigation";
import TagBrands from "@/components/tags/TagBrands";
import TagCategory from "@/components/tags/TagCategory";
import TagProducts from "@/components/tags/TagProducts";
import Description from "@/components/category/Description";
import CardContainer from "../../../../components/constantElements/CardContainer";
import SideBar from "@/components/category/SideBar";

export async function generateMetadata({ params, searchParams }) {
  let video = false;
  const slug = `tags/${params.tags}`;

  const dataFetch = await axios
    .get(`api/${slug}`)
    .then((result) => {
      return result;
    })
    .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());
      }
    });

  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;

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

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

  return {
    title: dataFetch.data.tag.title,
    description: dataFetch.data.tag.description,
    robots: {
      index: dataFetch.data.tag.index_status == 0 ? false : true,
      follow: dataFetch.data.tag.index_status == 0 ? false : true,
    },
    ...(video
      ? dataFetch.data.tag.products
        ? dataFetch.data.tag.products.next_page_url &&
          dataFetch.data.tag.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.tag.products.prev_page_url &&
            !dataFetch.data.tag.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.tag.products.next_page_url &&
            !dataFetch.data.tag.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.tag.products
      ? dataFetch.data.tag.products.next_page_url &&
        dataFetch.data.tag.products.prev_page_url
        ? {
            icons: {
              other: [
                {
                  rel: "next",
                  url: `${next}`,
                },
                {
                  rel: "prev",
                  url: `${prev}`,
                },
                {
                  rel: "preconnect",
                  url: backendUrl,
                },
              ],
            },
          }
        : dataFetch.data.tag.products.prev_page_url &&
          !dataFetch.data.tag.products.next_page_url
        ? {
            icons: {
              other: [
                {
                  rel: "prev",
                  url: `${prev}`,
                },
                {
                  rel: "preconnect",
                  url: backendUrl,
                },
              ],
            },
          }
        : dataFetch.data.tag.products.next_page_url &&
          !dataFetch.data.tag.products.prev_page_url
        ? {
            icons: {
              other: [
                {
                  rel: "next",
                  url: `${next}`,
                },
                {
                  rel: "preconnect",
                  url: backendUrl,
                },
              ],
            },
          }
        : {
            icons: {
              other: [
                {
                  rel: "preconnect",
                  url: backendUrl,
                },
              ],
            },
          }
      : null),
  };
  
}

export default async function Tags({ params, searchParams }) {
  const slug = `tags/${params.tags}`;

  const fetchedData = await axios
    .get(`api/${slug}`)
    .then((result) => result)
    .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 (
    <>
      <BreadcrumbCustom
        parentId={null}
        categorySlug={fetchedData.data.tag.slug}
        categoryName={fetchedData.data.tag.name}
        type="tag"
        // structure={dataFetch.data.brand.json_bread_crumb}
      />

      <section className="grid grid-flow-row grid-cols-9 sm:px-4 px-2 py-4 gap-4 w-full">
        <SideBar
          sideBanner={fetchedData.data.side_banners}
          popularData={fetchedData.data.popular_sliders}
          className="col-span-2 xl:block hidden"
          type="brand"
        />

        <section className="xl:col-span-7 col-span-9">
          {/* برند ها */}
          {fetchedData.data.tag.brands &&
            fetchedData.data.tag.brands.length > 0 && (
              <TagBrands data={fetchedData.data} />
            )}

          {/* دسته بندی ها */}
          {fetchedData.data.tag.categories &&
            fetchedData.data.tag.categories.length > 0 && (
              <TagCategory data={fetchedData.data} />
            )}

          {/* توضیحات کوتاه */}
          {fetchedData.data.tag.introduction && (
            <Description
              type="default"
              body={fetchedData.data.tag.introduction}
              className="my-12 last:mb-0"
            />
          )}

          {/* محصولات */}

          <div>
            <div
              className={`font-medium mb-2 sm:border-b-0 sm:p-0 p-2 border-b`}
            >
              {fetchedData.data.tag.name} بر اساس محصول:
            </div>

            {fetchedData.data.tag.products && (
              <CardContainer
                apiData={fetchedData.data.tag}
                type="tags"
                pages={searchParams.page}
              />
            )}
          </div>

          {fetchedData.data.tag.body && (
            <Description
              type="default"
              body={fetchedData.data.tag.body}
              className="my-12 last:mb-0"
            />
          )}
        </section>
      </section>
    </>
  );
}
