"use client";

import AddCard from "@/components/common/addCard/AddCard";
import LatestNewsVertical from "@/components/common/latestNews/LatestNewsVertical";
import { NewsItem } from "@/interface/post";
import TimeBefore from "@/ui/TimeBefore";
import NotFoundBody from "@/ui/notFoundBody/NotFoundBody";
import Spin from "@/ui/spin/Spin";
import ThreeDotsLoader from "@/ui/threeDotsLoader/ThreeDotsLoader";
import fetcher from "@/utils/fetcher";
import instance from "@/utils/instance";
import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import useSWR from "swr";
import notFoundImg from "@/public/images/not-found.png";
import CategoryPageSkeleton from "@/components/skeleton/CategoryPageSkeleton";
import { useTheme } from "next-themes";
import AddBanner from "../common/addBanner/AddBanner";
import AdsComponent from "../common/googleAds/GoogleAds";

interface TopicType {
  topic_name: string;
  slug: string;
}

const CategoryMain = () => {
  // const { theme } = useTheme();

  // const [pageData, setPageData] = useState<any[]>([]);
  // const [isPageDataLoading, setIsPageDataLoading] = useState(false);
  // const [limit, setLimit] = useState(15);

  const param = useParams();

  const {
    data,
    error,
    isLoading,
  }: { data: any; error: any; isLoading: boolean } = useSWR(
    `/category-post/${param.categoryName}?page_number=${0}`,
    fetcher
  );

  const [pageNumber, setPageNumber] = useState(0);

  if (error) return <div>Error loading data</div>;
  if (isLoading) return <div>Loading...</div>;


  const itemsPerPage = 13
  const totalPages = Math.ceil(data?.posts?.length / itemsPerPage)
  const startIndex = pageNumber * itemsPerPage
  const visiblePost = data?.posts?.slice(startIndex, startIndex + itemsPerPage)
  // console.log(visiblePost,"category")



  // useEffect(() => {
  //   if (pageNumber > 0) {
  //     (async () => {
  //       setIsPageDataLoading(true);
  //       try {
  //         const { data } = await instance.get(
  //           `/category-post/${param.categoryName}?page_number=${pageNumber}&limit=${limit}`
  //         );

  //         // setPageData((prev) => [...prev, ...data.data.posts]);
  //       } catch (error) {
  //         console.error(error);
  //       } finally {
  //         setIsPageDataLoading(false);
  //       }
  //     })();
  //   }
  // }, [pageNumber, param.categoryName]);

  // console.log(data,"ShowMore")
  // decide what to render
  //@TODO: When the error occurred
  if (error)
    return <NotFoundBody title={` ${error.message}`} img={notFoundImg} />;

  //@TODO: When the loading
  if (isLoading) return <CategoryPageSkeleton />;

  //@TODO: When No data found
  if (!data?.posts?.length)
    return (
      <NotFoundBody title="">
        <h2 className="text-7xl ">404</h2>
        <h3 className="text-2xl my-1 ">Not found anything</h3>
        <p className="">
          What you are looking for was not found. Maybe you&apos;re looking for it
          wrong.
        </p>
        <div className="mt-10">
          <Link
            href="/"
            className="text-lg text-white py-2 px-4 bg-[var(--primary)]  rounded-md"
          >
            Back to Home
          </Link>
        </div>
      </NotFoundBody>
    );
  const adsSlot1 = "1431883232"
  const adsSlot2 = "8681432265"
  const adsSlot3 = "8974497186"
  const adsSlot4 = "7742920966"

  return (
    <section className="pt-[20px]">

      {/* {data?.add.category_22 && (
        <AddBanner imgPath={data?.add.category_22} clss="mt-5" />
      )} */}

      <div className="container flex items-center justify-center px-4 sm:px-[60px] md:px-[36px] lg:px-[36px] mx-auto">
        <div
          className="w-full bg-[#f9f9f9] p-2 text-center mt-5"
          style={{ minWidth: "300px" }} // Add this
        >
          <AdsComponent
            adSlot="1431883232"
            style={{
              display: "block",
              minHeight: "90px",
              width: "100%",
              textAlign: "center",
            }}
          />
        </div>
      </div>


      <div className="container px-4 md:px-[37px] lg:px-[38px] xl:px-[40px]  mx-auto">
        <div className="mb-3">
          <div className="my-4">
            <Link className="block w-fit text-[16px]" href={`/${param?.categoryName}`}>
              <h1 className="block text-[var(--gray-1)]  dark:text-[var(--slate)]">
                {<Link className="hover:text-[#B42424] text-[#CCCCCC]"
                  href="/">Home / </Link>}  <span className="text-[#B42424]">{`${data?.posts[0]?.category_name}`}</span>
              </h1>
            </Link>
          </div>
          <div className="mb-0 py-0 md:py-1 lg:py-2 xl:py-2">
            {data?.topics?.map((category: TopicType, i: number) => {
              const { topic_name, slug } = category;
              return (
                <Link
                  key={i}
                  className=' text-lg mr-3 last:mr-0 relative after:text-[var(--dark)] after:content-["-"] after:ml-3 last:after:hidden  dark:after:text-[var(--gray-2)] '
                  href={`/topic/${slug}`}
                >
                  {topic_name}
                </Link>
              );
            })}
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-12 gap-6 mb-[30px] relative after:bg-[var(--border-color)]  dark:after:bg-[var(--border-dark)]">
          {visiblePost.slice(0, 1).map((itm: NewsItem) => {
            const {
              category,
              news_id,
              post_title,
              encode_titl,
              stitle,
              image_large,
            } = itm;
            return (
              <div
                key={news_id}
                className={`col-span-12 ${data?.add?.category_21 || data.add?.category_24 ? "lg:col-span-8 xl:col-span-9" : "lg:col-span-12 xl:col-span-12"} relative after:bg-[var(--border-color)]  dark:after:bg-[var(--border-dark)]`}
              >
                <div className="flex flex-col md:flex-row gap-5 md:gap-5 group">
                  <div className="w-auto md:w-1/2 lg:w-2/5 xl:w-[52.5%] order-2  sm:my-[25px] md:mr-[25px] md:ml-[15px] md:my-0  lg:mr-[30px] lg:ml-[15px] lg:my-0 xl:my-0 xl:mr-[33px] xl:ml-[20px]">
                    <Link
                      href={`/${category.toLocaleLowerCase()}/${encode_titl}`}
                    >
                      <h2 className="text-[20px] md:text-[28px] leading-[25px] md:leading-[36px] text-[var(--dark)] dark:text-white mb-3 md:mb-3 font-semibold">
                        {post_title}
                      </h2>
                      <p className="md:line-clamp-4 lg:line-clamp-3 xl:line-clamp-6 text-[16px] md:text-[20px] text-[var(--gray-2)] dark:text-[var(--gray-3)]">
                        {stitle}
                      </p>
                    </Link>


                    <ul className="mt-5 xl:mt-10">
                      {/* {visiblePost?.slice(1, 4).map((itm: NewsItem) => {
                        const { encode_titl, post_title, news_id } = itm;
                        return (
                          <li
                            key={news_id}
                            className="before:h-2 before:w-2 before:rounded-full before:bg-black before:border relative before:absolute before:top-2 before:left-0"
                          >
                            <Link
                              href={`/${category.toLocaleLowerCase()}/${encode_titl}`}
                              className="line-clamp-1 text-lg font-medium left-9 text-[var(--dark)] mb-2 mr-2 md:mr-0 ml-4    dark:text-white   "
                            >
                              {post_title}
                            </Link>
                          </li>
                        );
                      })} */}
                    </ul>
                  </div>
                  <Link
                    href={`/${category.toLocaleLowerCase()}/${encode_titl}`}
                    className="w-full md:w-1/2 lg:w-3/5 xl:w-[69.5%] rounded-[5px] overflow-hidden order-1 relative"
                  >
                    <div>
                      <Image
                        alt={post_title}
                        width={560}
                        height={315}
                        decoding="async"
                        className={`${data.add.category_21 || data.add?.category_24 ? "md:w-[390px] md:h-[290px] lg:w-[550px] lg:h-[340px] xl:w-[500px] xl:h-[255px]" : "md:w-[350px] md:h-[300px] lg:w-[550px] lg:h-[300px] xl:w-[600px] xl:h-[245px]"}w-full  h-auto  object-cover group-hover:scale-105 duration-700 ease-out`}
                        src={image_large}
                      />
                    </div>
                  </Link>
                </div>
              </div>
            );
          })}

          {(adsSlot2 || adsSlot2) && (
            <div className="col-span-12 md:col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] after:absolute after:w-full after:h-[1px] after:-bottom-3 after:right-0 after:last:h-0 md:after:w-[1px] md:after:h-full md:after:top-0 md:after:-right-3 md:after:last:w-0 dark:after:bg-[var(--border-dark)]">
              <div className="w-full flex flex-row lg:flex-col lg:h-full lg:flex lg:items-center justify-center gap-4">
                {adsSlot2 && (
                  <div className={`${adsSlot2 ? "w-full flex items-center justify-center" : "w-full flex items-center justify-center hidden"} bg-[#f9f9f9]`}>
                    <div className="h-[250px] min-w-[300px] w-full">
                      { /* home ads 14 here */}
                      <AdsComponent adSlot={adsSlot2} style={{
                        display: "block",
                        width: "100%",
                        minHeight: "251px",
                        textAlign: "center",

                      }} />

                    </div>
                  </div>
                )}

                {adsSlot1 && (
                  <div className={`${adsSlot2 ? "w-full flex items-center justify-center hidden sm:flex lg:hidden" : "w-full flex items-center justify-center"} bg-[#f9f9f9]`}>
                    <div className="h-[250px] min-w-[300px] w-full">
                      { /* home ads 14 here */}
                      <AdsComponent adSlot={adsSlot1} style={{
                        display: "block",
                        width: "100%",
                        minHeight: "251px",
                        textAlign: "center",

                      }} />

                    </div>
                  </div>
                )}
              </div>
            </div>
            // </div>
          )}



        </div>

        <div className="w-auto relative">
          <div className="grid grid-cols-1 md:grid-cols-12 gap-[24px]">


            <div className="col-span-12 lg:col-span-8 xl:col-span-9 relative after:bg-[var(--border-color)] dark:after:bg-[var(--border-dark)]">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mr-0 lg:mr-[40px] xl:mr-[50px] mb-6 dark:before:[&>*]:bg-[var(--border-dark)]">
                {visiblePost?.slice(1, 13).map((itm: NewsItem) => {
                  const {
                    category,
                    news_id,
                    post_date,
                    post_title,
                    encode_titl,
                    image_thumb,
                  } = itm;
                  return (
                    <div
                      key={news_id}
                      className="relative md:mb-[15px] lg:mb-[20px] xl:mb-[20px] dark:bg-black"
                    >
                      <Link
                        className="group"
                        href={`/${category.toLocaleLowerCase()}/${encode_titl}`}
                      >
                        <div className="overflow-hidden rounded-[5px] relative float-left">
                          <div>
                            <Image
                              alt={post_title}
                              width={330}
                              height={186}
                              decoding="async"
                              className="w-[124px] h-auto md:w-[254px] md:h-[165px] lg:w-[204px] lg:h-[125px] xl:w-[294px] xl:h-[210px] object-cover group-hover:scale-105 duration-700 ease-out"
                              src={image_thumb}
                              loading="lazy"
                            />
                          </div>
                        </div>
                        <h2 className="text-[14px] px-[16px] md:px-1  pt-0 md:pt-[12px] text-[var(--dark)] dark:text-white line-clamp-2 overflow-hidden  ">
                          {post_title}
                        </h2>

                        {/* <div className="text-sm pl-5 text-[var(--dark)] dark:text-white line-clamp-2">
                          <TimeBefore title={post_date} />
                          </div> */}
                      </Link>
                    </div>
                  );
                })}

                {/* {pageData?.map((itm: NewsItem) => {
                const {
                  category,
                  news_id,
                  post_date,
                  post_title,
                  encode_titl,
                  image_thumb,
                } = itm;
                return (
                  <div
                    key={news_id}
                    className="col-span-12 md:col-span-6 relative"
                  >
                    <Link
                      href={`/${category.toLocaleLowerCase()}/${encode_titl}`}
                    >
                      <div className="ml-3 mb-2 xl:mb-0 overflow-hidden float-right relative">
                        <div>
                          <Image
                            alt={post_title}
                            width={330}
                            height={186}
                            decoding="async"
                            className="w-[124px] h-auto lg:w-[110px] lg:h-[75px] xl:w-[180px] xl:h-[120px] object-cover group-hover:scale-105 duration-700 ease-out"
                            src={image_thumb}
                            loading="lazy"
                          />
                        </div>
                      </div>
                      <h2 className="text-lg text-[var(--dark)]    dark:text-white   ">
                        {post_title}
                      </h2>

                      <TimeBefore title={post_date} />
                    </Link>
                  </div>
                );
              })} */}
              </div>

              {/* {data?.posts_count >= data?.posts.length + pageData?.length ? (
              <div className="flex justify-center">
                <button
                  className="flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed text-white text-lg bg-[var(--primary)] px-4 py-2 hover:bg-[var(--primary)] rounded-sm "
                  disabled={isPageDataLoading}
                  onClick={() => {
                    setPageNumber((prev) => prev + 1);
                  }}
                >
                  See more {isPageDataLoading && <Spin clss="w-7 h-7" />}
                </button>
              </div>
            ) : (
              ""
            )} */}

              {/* <div className=" flex items-center justify-center pr-4 sm:pr-[60px] md:pr-[36px] lg:pr-[36px] mx-auto">
                <div className="w-full bg-[#f9f9f9] p-2 text-center mt-2 ">
                 
                  <AdsComponent adSlot={adsSlot4}  style={{
                        display: "block",
                        width: "100%",
                        minHeight: "251px",
                        textAlign: "center",
                        
                      }} />
                </div>
              </div> */}

              <div className="py-5 mr-0 lg:mr-[40px] xl:mr-[50px] mx-auto">
                <div className="flex justify-between mt-4 mb-6 bg-[#F2F2F2] rounded-[5px]">
                  <button
                    className="text-[#B42424] font-semibold px-4 py-5 rounded disabled:opacity-50 hover:bg-[#B42424] hover:text-white transition duration-300 text-[12px] md:text-[16px]"
                    disabled={pageNumber === 0}
                    onClick={() => setPageNumber((prev) => prev - 1)}
                  >
                    <span className="text-lg ">«</span> Previous Page
                  </button>
                  <button
                    className="text-[#B42424] font-semibold px-4 py-5 rounded disabled:opacity-50 hover:bg-[#B42424] hover:text-white transition duration-300 text-[12px] md:text-[16px]"
                    disabled={pageNumber + 1 >= totalPages}
                    onClick={() => setPageNumber((prev) => prev + 1)}
                  >
                    Next Page <span className="text-lg">»</span>
                  </button>
                </div>
              </div>


            </div>
            <div className="col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] after:absolute after:w-full after:h-[1px] after:-bottom-3 after:right-0 after:last:h-0 lg:after:w-[1px] lg:after:h-full lg:after:-right-3 lg:after:top-0 lg:after:last:w-0 dark:after:bg-[var(--border-dark)]">
              <div className="-mt-3">
                <div>
                  <div className="border-[#B42424] dark:border-[#B42424] border-b-[5px] mb-3 pb-1"></div>
                  <div>
                    <div className="mt-3 mb-3 ">
                      <h4 className="text-[var(--primary)] text-xl md:text-2xl dark:text-white font-bold">
                        Latest news
                      </h4>
                    </div>
                  </div>
                  <LatestNewsVertical />

                </div>
              </div>
              {/* {visiblePost?.length > 6 && (
                (data?.add?.category_23 || data?.add?.category_24) && (
                  <div className="col-span-12 md:col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] after:absolute after:w-full after:h-[1px] after:-bottom-3 after:right-0 after:last:h-0 md:after:w-[1px] md:after:h-full md:after:top-0 md:after:-right-3 md:after:last:w-0 dark:after:bg-[var(--border-dark)]">
                    <div className="w-full flex flex-row lg:flex-col lg:h-full lg:flex lg:items-center justify-center gap-4 mt-[40px]">
                      <div className={`${data?.add?.category_23 ? "w-full flex items-center justify-center" : "w-full flex items-center justify-center hidden"}`}>
                        <div className="h-[250px]">
                          <AddCard imgPath={data?.add?.category_23} />
                        </div>
                      </div>
  
                      <div className={`${data?.add?.category_23 ? "w-full flex items-center justify-center hidden sm:flex" : "w-full flex items-center justify-center"} `} >
                        <div className="h-[250px]">
                          <AddCard imgPath={data?.add?.category_24} />
                        </div>
                      </div>
                    </div>
                  </div>
                )
              )} */}

              {visiblePost?.length > 6 && (
                (adsSlot3 || adsSlot1) && (
                  <div className="col-span-12 md:col-span-12 lg:col-span-4 xl:col-span-3 relative after:bg-[var(--border-color)] after:absolute after:w-full after:h-[1px] after:-bottom-3 after:right-0 after:last:h-0 md:after:w-[1px] md:after:h-full md:after:top-0 md:after:-right-3 md:after:last:w-0 dark:after:bg-[var(--border-dark)]">
                    <div className="w-full flex flex-row lg:flex-col lg:h-full lg:flex lg:items-center justify-center gap-4 mt-[40px]">
                      <div className={`${adsSlot3 ? "w-full flex items-center justify-center" : "w-full flex items-center justify-center hidden"} bg-[#f9f9f9]`}>
                        <div className="h-[250px] min-w-[300px] w-full">
                          { /* home ads 14 here */}
                          <AdsComponent adSlot={adsSlot3} style={{
                            display: "block",
                            width: "100%",
                            minHeight: "251px",
                            textAlign: "center",

                          }} />

                        </div>
                      </div>

                      <div className={`${adsSlot3 ? "w-full flex items-center justify-center hidden sm:flex" : "w-full flex items-center justify-center"} bg-[#f9f9f9]`} >
                        <div className="h-[250px] min-w-[300px] w-full">
                          { /* home ads 14 here */}
                          <AdsComponent adSlot={adsSlot1} style={{
                            display: "block",
                            width: "100%",
                            minHeight: "251px",
                            textAlign: "center",

                          }} />

                        </div>
                      </div>
                    </div>
                  </div>
                )
              )}



            </div>
          </div>
        </div>


      </div>
    </section>
  );
};

export default CategoryMain;
