import LayoutWithNav from "@/components/layout/LayoutWithNav";
import {
  classifiedCategories,
  classifiedCategoriesWithSubcategories,
  fetchAllAds,
} from "apiCalls/apiEndpoints";
import type { NextPage } from "next";
import Link from "next/link";
import Image from "next/image";
import { Button, Breadcrumb, Modal, Select, Input } from "antd";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { useInfiniteQuery, useQuery } from "react-query";
import OnpageSearch from "@/components/search/OnpageSearch";
import { NextSeo } from "next-seo";
import useInitGAd from "@/components/hooks/useInitGAd";
import { base_new_url, sortByNewest } from "utilFuncs/utilFunctions";
import SortingBy from "@/components/filter_tools/SortingBy";
import SortByTime from "@/components/filter_tools/SortByTime";
import useSort from "@/components/hooks/useSort";

const { Option } = Select;
const { Search } = Input;

const Ads: NextPage = ({ data, clwsc }: any) => {
  useInitGAd();

  const scrollToComponent = React.createRef();

  console.log(data?.allAds?.data?.data);

  const router = useRouter();
  const { page } = router.query;

  //fetch categories
  const { data: classifiedCategory, isLoading } = useQuery(
    "classifieds-categories",
    classifiedCategories
  );

  //sorted state data
  const {allAdsState, setallAdsState, sortByState, setsortByState, sortAdsBy, sortByTime, setSortByTime, sortAdsByTimePosted } =
    useSort(data?.allAds?.data?.data);

  //set sorted ads
  useEffect(() => {
    sortAdsBy();
  }, [sortByState]);



  useEffect(() => {
    sortAdsByTimePosted();
  }, [sortByTime]);

  let currentDate = new Date();



  const [sortedData, setsortedData] = useState([]);

  const [currentPage, setcurrentPage] = useState<number>(1);

  useEffect(() => {
    if (page === undefined) {
      setcurrentPage(0);
    }
  }, [page]);

  useEffect(() => {
    if (currentPage > 1) {
      router.push(`/ads?page=${currentPage}`);

      // router.query
    }
  }, [currentPage]);

  const handleNext = () => {
    let res = currentPage;

    router.push(`/ads?page=${(res += 1)}`);
    setcurrentPage((prev) => (prev += 1));
  };

  const handlePrev = () => {
    setcurrentPage((prev) => (prev -= 1));
  };

  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  //when a category is selected
  const onChange = (value: string) => {
    console.log(value);
    router.push(`/ads/${value}`);
  };

  //when a search query is made
  const onSearch = (value: string) => {
    console.log("search:", value);
  };

  //show modal when the search is clicked
  const handleSearchFocus = () => {
    setModal1Visible(true);
  };

  const handleSearchChange = () => [];

  const handleDecoyChange = () => {
    setModal1Visible(true);
  };

  const [currpage, setcurrPage] = useState(1);
  useEffect(() => {
    console.log("currpage", currpage);
  }, [currpage]);

  const fetchItems = async (key, currpage) => {
    const response = await fetch(
      `${base_new_url()}/api/v2/ads?page=${currpage}&include=getClassified,district`
    );
    const data = await response.json();
    return data;
  };

  const {
    data: adsData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isError,
    isLoading: adsLoading,
  } = useInfiniteQuery(
    "items",
    ({ pageParam = currpage }) => fetchItems("items", pageParam),
    {
      getNextPageParam: (lastPage) => {
        console.log("nextpage", lastPage.nextPage);
      }, // Assuming the API response provides a 'nextPage' field
    }
  );

  useEffect(() => {
    console.log("adsData", adsData);
  }, []);

  const handleScroll = () => {
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;
    const scrollPosition = window.scrollY;

    // Calculate the scroll position that represents scrolling halfway through the page
    const halfwayScrollPosition = (documentHeight - windowHeight) / 2;
    console.log("hlfwayposition", halfwayScrollPosition);

    if (
      scrollPosition >= halfwayScrollPosition &&
      !isFetchingNextPage &&
      hasNextPage
    ) {
      setcurrPage((prevPage) => prevPage + 1);
      fetchNextPage();
    }
  };

  // Attach the scroll event listener
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  const [modal1Visible, setModal1Visible] = useState(false);

  const fetch_ads = ({ pageParam = 1 }) =>
    fetch(`v2/ads?page=${pageParam}&include=getClassified,district`);

  return (
    <LayoutWithNav page_title="Ads">
      <NextSeo
        title={`All Ads in Ashanti Region, Buy and Sell the latest Items with us | Ashantiweb.com`}
        description={`All Ads in Ashanti Region, Buy and Sell the latest Items with us`}
      />
      <main className="container mx-auto px-2 lg:px-4 pt-3">
        {/* mobile version */}
        <section className="md:hidden">
          <div className="container overflow-auto overflow-y-scroll">
            <div className="mb-2">
              <Breadcrumb>
                <Breadcrumb.Item>
                  <Link href={"/"}>Ashantiweb</Link>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                  <Link href={"/ads"}>Classifieds</Link>
                </Breadcrumb.Item>

                {/* <Breadcrumb.Item>{ads_category?.toString().replace('-', ' ')}</Breadcrumb.Item> */}
              </Breadcrumb>
            </div>

            <OnpageSearch category={"all categories"} unReplacedString={""} />

            {/* <div className="my-2">
              <Search onClick={handleSearchFocus} onChange={handleDecoyChange} placeholder="Search Any Item..." onSearch={onSearch} enterButton />
              <Modal
                title="Search"
                style={{ top: 5 }}
                visible={modal1Visible}
                onOk={() => setModal1Visible(false)}
                onCancel={() => setModal1Visible(false)}
              >
               <Search autoFocus={true} onChange={handleSearchChange} placeholder="Search for anything" onSearch={onSearch} enterButton />
              </Modal>
            </div> */}

            <div className="my-2">
              <Button onClick={showModal}>Filter Ads</Button>
              <Modal
                title="Apply Filters"
                visible={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                style={{ top: 5 }}
              >
                <Select
                  // showSearch
                  placeholder={"Select a category"}
                  optionFilterProp="children"
                  className="w-full"
                  onChange={onChange}
                  onSearch={onSearch}

                  // filterOption={(input, option) =>
                  //   (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                  // }
                >
                  {" "}
                  {classifiedCategory?.data.data.map(
                    (item: any, index: number) => (
                      <Option key={index} value={item.slug}>
                        {item.name}
                      </Option>
                    )
                  )}
                </Select>
              </Modal>
            </div>

            {/* <input type="text" className='border-2 inline'/> */}
            {/* <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select>
            <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select>
            <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select>
            <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select>
            <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select>
            <select name="" id="">
              <option value="">one</option>
              <option value="">two</option>
              <option value="">three</option>
            </select> */}
          </div>
          <div className="container">
            <div className="mb-4 flex justify-end">
              <div className="text-gray-600">
                <SortingBy setSortBy={setsortByState} /> |{" "}
                <span className="font-bold">{sortByState}</span> |{" "}
                <SortByTime setSortByTime={setSortByTime} /> :{" "}
                <span className="font-bold">{sortByTime}</span>
              </div>
            </div>
            <div className="grid gap-4 grid-cols-1 grid-rows-3">
              {allAdsState.map((ad: any, index) => (
                <Link
                  href={`ad/${ad?.slug}`}
                  key={index}
                  className="cursor-pointer"
                  passHref
                >
                  {true ? (
                    // horizontal layout
                    <a>
                      <div
                        key={index}
                        className="cursor-pointer border flex flex-start shadow-md rounded-md"
                      >
                        <Image
                          width="192"
                          height="160"
                          objectFit="cover"
                          src={ad?.picture}
                          alt={ad?.name}
                          placeholder="blur"
                          blurDataURL="/assets/images/preloader/preloader-static6.png"
                        />

                        <div className="p-2 ml-2">
                          <p className="font-normal text-gray-700 mb-2">
                            {ad?.name}
                          </p>
                          <p className="font-bold text-green-500 mt-2">
                            {ad?.currency} {ad?.price}
                          </p>
                        </div>
                      </div>
                    </a>
                  ) : (
                    // vertical layout although this is horizontal layout
                    <a>
                      <div
                        key={index}
                        className="cursor-pointer border flex flex-start shadow-md rounded-md"
                      >
                        <div className="h-40 w-48 md:h-44 lg:h-52 relative">
                          <Image
                            width="192"
                            height="160"
                            objectFit="cover"
                            src={ad?.picture}
                            alt={ad?.name}
                            placeholder="blur"
                            blurDataURL="/assets/images/preloader/preloader-static6.png"
                          />
                        </div>
                        <div className="p-2 ml-2">
                          <p className="font-normal text-gray-700 mb-2">
                            {ad?.name}
                          </p>
                          <p className="font-bold text-green-500 mt-2">
                            {ad?.currency} {ad?.price}
                          </p>
                        </div>
                      </div>
                    </a>
                  )}
                </Link>
              ))}
            </div>
          </div>
        </section>
        {/* ./mobile version */}

        <div className="hidden container mx-auto md:flex mt-10">
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link href={"/"}>Ashantiweb</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link href={"/ads"}>classifieds</Link>
            </Breadcrumb.Item>
          </Breadcrumb>
        </div>

        {/* desktop */}
        <section className="hidden md:flex">
          <div className="w-4/12 lg:w-2/12 mt-5">
            <div className="rounded-md shadow-sm">
              <div className="bg-white rounded-md shadow-sm p-3">
                <p className="font-bold text-gray-600">Categories</p>
                <ul className="">
                  {clwsc.map((clwsc: any, index: number) => (
                    <Link key={index} href={`/ads/${clwsc.slug}`} passHref>
                      <a className="block">
                        <li className="font-normal text-gray-500 p-2 hover:bg-gray-300 rounded-md cursor-pointer flex items-center">
                          {/* <Image width={10}/> */}
                          <div className="w-8 h-8 relative mr-3">
                            <Image layout="fill" src={clwsc.picture} />
                          </div>
                          {clwsc.name}
                        </li>
                      </a>
                    </Link>
                  ))}
                </ul>
              </div>
            </div>
          </div>
          {/* w-8/12 lg:w-7/12 */}
          <div className="w-8/12 lg:w-10/12 mt-5">
            <div>
              {/* <ins className="adsbygoogle"
                // style="display:block"
                style={{ display: 'block' }}
                data-ad-client="ca-pub-1110030198957831"
                data-ad-slot="9306370885"
                data-ad-format="auto"
                data-full-width-responsive="true"></ins> */}
            </div>

            <div className="ml-4">
              <div className="mb-4 flex justify-end">
                <div className="text-gray-600">
                  <SortingBy setSortBy={setsortByState} /> |{" "}
                  <span className="font-bold">{sortByState}</span> |{" "}
                  <SortByTime setSortByTime={setSortByTime} /> :{" "}
                  <span className="font-bold">{sortByTime}</span>
                </div>
              </div>
              <div className="grid gap-4 grid-cols-1 lg:grid-cols-2 grid-rows-3">
                <>
                  {/* {adsData?.pages?.map((pageData: any) => (
                    <>
                      {pageData.data.data.map((ad: any, index: any) => (
                      
                        <Link
                          href={`ad/${ad?.slug}`}
                          key={index}
                          className="cursor-pointer"
                          passHref
                        >
                          <a>
                            <div
                              key={index}
                              className="cursor-pointer border shadow-md rounded-md"
                            >
                              <div className="h-40 md:h-44 lg:h-52 w-full relative">
                                <Image
                                  layout="fill"
                                  src={ad?.picture}
                                  alt={ad?.name}
                                  placeholder="blur"
                                  blurDataURL="/assets/images/preloader/preloader-static6.png"
                                />
                              </div>
                              <div className="p-2">
                                <p className="font-normal text-gray-700 h-12 mb-2">
                                  {ad?.name?.slice(0, 30)}
                                </p>
                                <p className="font-bold text-green-500 mt-2">
                                  {ad?.currency} {ad?.price}
                                </p>
                              </div>
                            
                            </div>
                          </a>
                        </Link>
                      ))}
                    </>
                  ))} */}
                  {allAdsState.map((ad: any, index) => (
                    <Link
                      href={`ad/${ad?.slug}`}
                      key={index}
                      className="cursor-pointer"
                      passHref
                    >
                      <a>
                        <div
                          key={index}
                          className="cursor-pointer border shadow-md rounded-md flex"
                        >
                          <div className="h-40 w-1/2 md:h-44 lg:h-52 relative">
                            <Image
                              layout="fill"
                              src={ad?.picture}
                              objectFit="cover"
                              alt={ad?.name}
                              placeholder="blur"
                              blurDataURL="/assets/images/preloader/preloader-static6.png"
                            />
                          </div>
                          <div className="p-2 ml-2 w-1/2">
                            <div className="font-normal text-gray-700  mb-2">
                              {ad?.name}
                            </div>

                            {ad?.priceAsInt ? (
                              <div className="font-bold text-green-500 mt-2">
                                {ad?.currency} {ad?.price}
                              </div>
                            ) : (
                              ""
                            )}
                          </div>
                        </div>
                      </a>
                    </Link>
                  ))}
                </>
              </div>
              <div className="center">
                {adsLoading || isFetchingNextPage ? (
                  <p>loading, please wait...</p>
                ) : null}
              </div>

              {/* <button
                onClick={() => {
                  setcurrPage((prevPage) => prevPage + 1);
                  fetchNextPage();
                }}
              >
                fetch next page
              </button> */}

              {/* <div className="center">
                {!hasNextPage && <div>Reached the end</div>}
              </div> */}
            </div>
          </div>
        </section>

        {/* <div className='flex justify-center mt-5'> */}
        {/* <Paginator entity={ads} scrollToComponent={scrollToComponent} /> */}
        {/* <Paginator entity={data?.allAds?.data?.data} scrollToComponent={scrollToComponent} /> */}
        {/* </div> */}
      </main>
    </LayoutWithNav>
  );
};

export async function getServerSideProps({ req, res, params, query }: any) {
  res.setHeader(
    "Cache-Control",
    "public, s-maxage=10, stale-while-revalidate=59"
  );

  let data;

  if (query?.page === undefined) {
    data = await fetchAllAds();
  } else {
    data = await fetchAllAds(query?.page);
  }

  const classifiedsWithSubCategories =
    await classifiedCategoriesWithSubcategories();

  return {
    props: {
      data: {
        allAds: data.data,
      },
      clwsc: classifiedsWithSubCategories.data.data,
    }, // will be passed to the page component as props
  };
}

export default Ads;
