import LayoutWithNav from "@/components/layout/LayoutWithNav";
import { fetchDistricts, fetchSingleAd } from "apiCalls/apiEndpoints";
import type { NextPage } from "next";
import { useRouter } from "next/router";
import SwiperCore, { Navigation, Pagination } from "swiper";
import { Swiper, SwiperSlide } from "swiper/react";
import PopupGallery from "components/popup_gallery/popup-gallery";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { Button, Col, PageHeader, Row, Typography } from "antd";
import { CaretRightOutlined } from "@ant-design/icons";
import Link from "next/link";
import { useDistricts } from "context/DistrictContext";
import ImageWithFallback from "@/components/layout/ImageWithFallback";
import StandardContainer from "@/components/layout/StandardContainer";
import SingleAd from "@/components/featured_ads/SingleAd";
import { NextSeo } from "next-seo";
import { containsHTMLTags, isProduction } from "utilFuncs/utilFunctions";
// import {parse} from parse
import parse, { domToReact } from "html-react-parser";
import { useUser } from "context/UserContext";

const Ad: NextPage = ({ data }: any) => {
  const router = useRouter();
  const { ad_slug } = router.query;
  const { singleAd } = data;

  const { setDistricts } = useDistricts();
  const { user, isAuthenticated } = useUser();

  useEffect(() => {
    setDistricts(data?.districts);
  }, [data?.districts, setDistricts]);

  const [opsSliderLength, setOpSliderLength] = useState(1);

  React.useEffect(() => {
    if (singleAd?.ops?.length && singleAd?.ops?.length > 1) {
      if (singleAd?.ops?.length == 2) {
        setOpSliderLength(2);
      }
      setOpSliderLength(Math.ceil(singleAd?.ops?.length / 2));
    }
  }, [singleAd]);

  SwiperCore.use([Navigation, Pagination]);

  const sliderSettings = {
      slidesPerView: opsSliderLength,
      spaceBetween: 5,
      navigation: true,
      pagination: { clickable: true },
      style: { maxWidth: "300px" },
    },
    [description, setDescription] = useState<any>(true),
    swapDesRev = (e: any) => {
      e.preventDefault();
      setDescription(!description);
    };


  const options = {
    replace: ({ attribs, children }) => {

      console.log('attribs', attribs);
      return (
        <p style={{ width: '100%', wordBreak: 'break-word', maxWidth: '400px' }} className="text-gray-600">
          {domToReact(children)}
        </p>
      );
      // {domToReact(children)}
      // if (!attribs) {
      //   return;
      // }

      // if (attribs.id === 'main') {
      //   return <h1 style={{ fontSize: 42 }}>{domToReact(children, options)}</h1>;
      // }

      // if (attribs.class === 'prettify') {
      //   return (
      //     <span style={{ color: 'hotpink' }}>
      //       {domToReact(children, options)}
      //     </span>
      //   );
      // }
    },
  };

  return (
    <LayoutWithNav page_title="Ads">
      <NextSeo
        title={`${singleAd?.name} | Ashantiweb.com`}
        description={`${singleAd?.name} in Kumasi`}
      />
      <StandardContainer>
        {/* {isProduction() && true ? (<div className='container mx-auto md:flex center mt-16'>
                    <div className='w-11/12 h-40 bg-gray-400 text-black center'>
                        Ad space
                    </div>
                </div>) : ''} */}

        <section className="bg-white">
          <section className="ads-details-page">
            <div className="row">
              <div className="col-lg-9">
                <div className="ads-details pt-20">
                  <div className="row">
                    <div className="col-md-7">
                      <div
                        className="ads-details-image mt-30 pb-10"
                        style={{ background: "#f7f7f7" }}
                      >
                        <div className="details-image">
                          <div className="single-details-image d-flex justify-content-center align-items-center">
                            {/* <p>image here</p> */}
                            <Image
                              // layout='fill'
                              width={495}
                              height={495}
                              src={singleAd?.picture}
                              alt={singleAd?.name}
                            />
                          </div>
                        </div>

                        <div className="mt-20">
                          {singleAd?.ops?.length ? (
                            <Swiper {...sliderSettings}>
                              {singleAd?.ops?.map((op: any) => (
                                <SwiperSlide
                                  key={op}
                                  className="single-details-image"
                                >
                                  <PopupGallery
                                    media={singleAd?.ops.map((o: any) => ({
                                      src: o,
                                      
                                    }))}
                                    currentMediaIndex={singleAd?.ops?.indexOf(
                                      op
                                    )}
                                  >
                                    {(onClick: any) => (
                                      // <p>ricketty boy from the 90s</p>
                                      // <></>
                                      <Image
                                        //   style={{ height: "80px" }}
                                        //   layout="fill"
                                        width={160}
                                        height={160}
                                        src={op}
                                        alt={singleAd?.name}
                                        onClick={onClick}
                                      />
                                    )}
                                  </PopupGallery>
                                </SwiperSlide>
                              ))}
                            </Swiper>
                          ) : null}
                        </div>
                      </div>
                    </div>
                    <div className="col-md-5">
                      <div className="ads-details-content mt-5">
                        <h4 className="title">{singleAd?.name}</h4>

                        <ul className="rating">
                          {singleAd?.rating?.map((rt: any) => (
                            <li key={rt.id} className="active">
                              <i className="far fa-star"></i>
                            </li>
                          ))}
                        </ul>

                        {/* <p className="reviews"><strong>Views: {ad?.views?.length}</strong> {ad?.ratings?.length} Review{ad?.ratings?.length !== 1 ? 's' : null}</p> */}

                        {singleAd?.priceAsInt ? (
                          <p
                            style={{
                              fontSize: "13px",
                              color: "red",
                              margin: 0,
                            }}
                            className="font-2"
                          >
                            {singleAd?.currency + singleAd?.price}
                          </p>
                        ) : null}
                        <div className="ads-details-wrapper">
                          <div className="share">
                            {/* <Share title={ad?.name} text={ad?.description} url={'/ad/' + ad?.slug} /> */}
                          </div>

                          <div className="ads-details-contact">
                            <h6 className="title">Call now</h6>

                            <div className="d-block">
                              {/* <QuickChat contactText='Contact Seller' secondPerson={ad?.originalPoster} /> */}
                            </div>
                            <div className="ads-details-contact-wrapper d-flex flex-wrap align-items-center mt-2">
                              {singleAd?.advertiser?.phone ? (
                                <div className="px-2 py-3 text-white rounded-md bg-black flex items-center justify-center">
                                  <div>
                                    <a
                                      className="text-2xl"
                                      href={
                                        "tel:" + singleAd?.advertiser?.phone
                                      }
                                    >
                                      {singleAd?.advertiser?.phone}
                                    </a>
                                    <p>Phone Number</p>
                                  </div>
                                  <i className="fal fa-phone ml-1"></i>
                                </div>
                              ) : null}
                              {singleAd?.advertiser?.email ? (
                                <div className="ads-details-message">
                                  <a
                                    href={
                                      "mailto:" + singleAd?.advertiser?.email
                                    }
                                  >
                                    <i className="fal fa-envelope-open-text"></i>
                                  </a>
                                </div>
                              ) : null}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="Product-tab mt-50">
                  <ul
                    className="nav justify-content-center"
                    id="myTab"
                    role="tablist"
                  >
                    <li>
                      <a
                        className={description ? "active" : ""}
                        onClick={(e) => swapDesRev(e)}
                        data-toggle="tab"
                        href="#"
                        role="tab"
                        aria-controls="description"
                        aria-selected={description}
                      >
                        description
                      </a>
                    </li>
                    <li>
                      <a
                        className={description ? "" : "active"}
                        onClick={(e) => swapDesRev(e)}
                        data-toggle="tab"
                        href="#"
                        role="tab"
                        aria-controls="review"
                        aria-selected={!description}
                      >
                        reviews
                      </a>
                    </li>
                  </ul>

                  <div className="tab-content" id="myTabContent">
                    <div
                      id="description"
                      className={
                        description
                          ? "tab-pane fade active show"
                          : "tab-pane fade"
                      }
                      role="tabpanel"
                      aria-labelledby="description-tab"
                    >
                      <div className="Product-tab-cont text-gray-600 text-md">
                       
                        {containsHTMLTags(singleAd?.description) ? parse(singleAd?.description, options)  : `${singleAd?.description}`  }
                      </div>
                    </div>

                    <div
                      id="review"
                      className={
                        description
                          ? "tab-pane fade"
                          : "tab-pane fade active show"
                      }
                      role="tabpanel"
                      aria-labelledby="review-tab"
                    >
                      
                    </div>
                  </div>
                </div>
              </div>
              <div className="col-lg-3">
                <div className="ads-sidebar pt-20">
                  <div className="sidebar-seller mt-25">
                    <div className="ads-sidebar-title">
                      <h4 className="title" style={{ fontSize: "17px" }}>
                        Seller Details
                      </h4>
                    </div>
                    <div className="single-seller-author mt-25">
                      <div className="seller-author-wrapper flex flex-col lg:flex-row center ">
                        <div className="author-image relative w-16 h-16">
                          <ImageWithFallback
                            src={singleAd?.advertiser?.picture}
                            alt={singleAd?.advertiser?.name}
                            layout="fill"
                          />
                        </div>
                        {singleAd?.advertiser_type == "App\\User" ? (
                          <div className="author-content media-body flex flex-col items-center lg:items-start">
                            <span className="online">Offline</span>
                            <h5 className="author-name">
                              {singleAd?.advertiser?.name}
                            </h5>
                            <Button
                              className=""
                              type="primary"
                              href={"/user/" + singleAd?.advertiser?.username}
                              target="_blank"
                            >
                              View Profile
                            </Button>
                          </div>
                        ) : null}
                        {singleAd?.advertiser_type == "App\\Shops" ? (
                          <div className="author-content media-body flex flex-col items-center lg:items-start">
                            {/* <span className="mt-2">Offline</span> */}
                            <h5 className="author-name">
                              {singleAd?.advertiser?.name}
                            </h5>

                            {isAuthenticated && (
                              <Button
                                className="mt-2"
                                type="primary"
                                href={"/user/" + user?.username}
                                target="_blank"
                              >
                                View Profile
                              </Button>
                            )}

                            {/* <Button
                              className="mt-2"
                              type="primary"
                              href={"/shop/" + singleAd?.advertiser?.slug}
                              target="_blank"
                            >
                              View Shop Page
                            </Button> */}
                          </div>
                        ) : null}
                      </div>
                      <div className="seller-about">
                        <h5 className="title">About</h5>
                        <p style={{ fontSize: "14px", color: "#444" }}>
                          {singleAd?.advertiser?.description}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="sidebar-ads mt-25">
                    {singleAd?.byuser?.length ? (
                      <>
                        <div className="side-header">
                          <h2>Advertiser Also Posted</h2>
                        </div>
                      </>
                    ) : null}

                    {singleAd?.byuser?.map((bu: any) => (
                      <div
                        key={bu.id}
                        className="single-popular-ads d-flex mt-30"
                      >
                        <div className="ads-thumb">
                          <Link href={"/ad/" + bu.slug} passHref>
                            <a className="relative h-20 w-20">
                              <ImageWithFallback
                                layout="fill"
                                src={bu.picture}
                                alt={bu.name}
                                style={{
                                  border: "solid #bfcac2 1px",
                                  borderRadius: "3px",
                                }}
                              />
                            </a>
                          </Link>
                        </div>
                        <Link
                          href={"/ad/" + bu.slug}
                          className="ads-content media-body"
                          passHref
                        >
                          <a className="ml-2">
                            <Typography.Title
                              ellipsis={{ rows: 2, expandable: false }}
                              style={{ fontSize: "14px" }}
                            >
                              {bu.name}
                            </Typography.Title>
                            <div className="price-rating d-flex align-items-center justify-content-between">
                              {bu.price ? (
                                <span
                                  className="price"
                                  style={{ fontSize: "12px", color: "red" }}
                                >
                                  {bu.currency + bu.price}
                                </span>
                              ) : null}
                              <ul className="rating">
                                {Array.from(
                                  Array(Number(bu.ratings)),
                                  (e, i) => (
                                    <li key={i}>
                                      <i className="fal fa-star"></i>
                                    </li>
                                  )
                                )}
                              </ul>
                            </div>
                          </a>
                        </Link>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </section>

          <section className="ads-area mt-5 mb-5">
            <div className="container">
              <div className="row">
                <div className="col-lg-9">
                  <div className="section-title text-center pb-10">
                    <PageHeader
                      className="site-page-header"
                      title={
                        <Link
                          style={{ fontSize: "24px" }}
                          className="text-dark"
                          href={"/" + singleAd?.classified?.slug}
                        >
                          Similar Ads
                        </Link>
                      }
                      subTitle={
                        <Link
                          className="text-dark"
                          href={"/ads/" + singleAd?.classified?.slug}
                        >
                          <a>
                            {singleAd?.classified?.name}
                            <CaretRightOutlined />
                          </a>
                        </Link>
                      }
                      style={{
                        borderTop: "3px solid green",
                        borderBottom: "1px solid green",
                        paddingTop: "7px",
                        paddingBottom: "7px",
                      }}
                    />
                  </div>
                  <div className="">
                    {/* <GridAdComponent mini ads={ad?.similar} /> */}
                    <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                      {singleAd?.similar.map((ad: any, i: number) => (
                        <div key={i}>
                          {ad?.id ? (
                            <SingleAd
                              name={ad?.name}
                              price={ad?.price}
                              slug={ad?.slug}
                              key={ad?.id}
                              picture={ad?.picture}
                              intprice={ad?.price}
                            />
                          ) : (
                            // <Link className=" mt-2" style={{ position: 'relative' }} href={'/ad/' + ad?.slug} passHref>
                            //     <a className='single-ads-product overflow-hidden'>
                            //         <div className="product-image d-block relative" style={{ minHeight: '140px', maxHeight: '20px' }}>
                            //             <ImageWithFallback layout='fill' style={{ width: '100%' }} src={ad?.picture} alt={ad?.name} />
                            //         </div>
                            //         <div className="product-content" style={{ paddingBottom: '0px !important' }}>
                            //             {/* <h6 className="sub-title">{ad?.classified?.name}</h6> */}
                            //             <Typography.Title level={4} ellipsis={{ rows: 2, expandable: false }} style={{
                            //                 fontSize: '13px', marginBottom: '1px',
                            //                 overflow: 'hidden'
                            //             }} className="main-title">
                            //                 {ad?.name}
                            //             </Typography.Title>
                            //             {!true
                            //                 ? (
                            //                     <>
                            //                         {ad?.price
                            //                             ? (
                            //                                 <div className="price-rating d-flex justify-content-between">
                            //                                     <p className="price" style={{ margin: '0 0 2px 0', color: 'red', fontSize: '13px' }}>{ad?.currency + ad?.price}</p>
                            //                                     {/* <ul className="rating">
                            // 			{ad?.ratings?.map(rating =>
                            // 				<li key={rating?.id}><i className="far fa-star"></i></li>
                            // 			)}
                            // 			</ul> */ }
                            //                                 </div>
                            //                             ) : null}
                            //                         {/* <p style={{ fontSize: '13px', margin: 0 }} className="location"><i className="far fa-map-marker-alt"></i> {ad?.district?.name}</p> */}
                            //                     </>
                            //                 ) : (
                            //                     <div className='w-100'>
                            //                         {ad?.price
                            //                             ? (
                            //                                 <p style={{ margin: '0 0 2px 0', color: 'green', fontSize: '13px' }} className="location"><i className="far">GH₵</i> {ad?.price}</p>
                            //                             ) : null}
                            //                         {/* <p style={{ fontSize: '13px', margin: 0 }} className="location"><i className="far fa-map-marker-alt"></i> {ad?.district?.name}</p> */}
                            //                     </div>
                            //                 )}

                            //         </div>
                            //     </a>
                            // </Link>
                            <div
                              style={{ height: "100%" }}
                              className="d-block single-ads-product mt-15"
                            >
                              {ad}
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="col-lg-3">
                  {singleAd?.similar?.length > 0 ? (
                    <div>
                      {/* <EHA
                                                localKey='lside'
                                                style={{ display: 'block' }}
                                                client="ca-pub-1110030198957831"
                                                slot="6238186276"
                                                width='100%'
                                                height='467px'
                                            /> */}
                    </div>
                  ) : null}
                </div>
              </div>
              <div className="row"></div>
            </div>
          </section>
        </section>
        <div className="container mx-auto md:flex center mt-16">
          {/* {isProduction() && false ? (<div className='w-11/12 h-40 bg-gray-400 text-black center'>
                    Ad space
                </div>) : ''} */}
        </div>
      </StandardContainer>
    </LayoutWithNav>
  );
};

// This gets called on every request
export async function getServerSideProps({ req, res, params }: any) {
  const { ad_slug } = params;
  console.log("ad_slug", ad_slug);

  // Fetch data from external API
  const singleAd = await fetchSingleAd(ad_slug);
  console.log(singleAd);

  // const res = await fetch(`https://.../data`)
  // const data = await res.json()

  // Pass data to the page via props

  const districts = await fetchDistricts();

  return {
    props: {
      data: {
        singleAd: singleAd.data,
        districts: districts.data,
      },
    },
  };
}

export default Ad;
