import { Button, Carousel } from "antd";
import React, { FC, useContext, useEffect, useState } from "react";
import {
  SampleNextArrow,
  SamplePrevArrow,
} from "../../../sellerLanding/common/ArrowDirections";
import styles from "./brandPage.module.scss";
import cx from "classnames";
import Image from "next/image";
import ImageSlider from "./imageSlider";
import { baseUrl } from "../../../../constants/urls";
import { useRouter } from "next/router";
import BrandStory from "./brandStory/brandStory";
import BrandVideoCard from "./brandStory/brandVideoCard";
import BrandFeaturedCategory from "./brandFeaturedCategory/brandFeaturedCategory";
import BrandFeaturedProducts from "./brandFeaturedCategory/brandFeaturedProducts";
import { VIEW_TYPES } from "../../../../constants/product";
import shopConetxt from "../../../../context/shopConetxt";
import * as CategoryAPI from "../../../../pages/api/category";
import axios from "axios";
import * as ProductAPIs from "../../../../pages/api/products";
import BrandLatestOffers from "./offers/brandLatestOffers";
import MediaQuery from "react-responsive";
import SEOHead from "../../../SEOHead";
import { description } from "../../../../mockData/seoConstants";

const brandPage: FC<any> = (props) => {
  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  });
  const {
    isProductListLoading,
    setIsProductListLoading,
    isFiltersLoading,
    setIsFiltersLoading,
    categoryBreadcrumb,
    setCategoryBreadcrumb,
  } = useContext(shopConetxt);

  const [isDataLoading, setIsDataLoading] = useState(false);
  const [products, setProducts] = useState<any>({ data: {}, meta: {} });
  const [productsES, setProductES] = useState<any>({
    hits: { total: { value: 0 }, hits: [] },
  });
  const [viewType, setViewType] = useState(VIEW_TYPES.GRID);
  const [filterVisible, setFilterVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [activeFilterConditions, setActiveFilterConditions] = useState({});
  const [category, setCategory] = useState([]);
  const [categoryTree, setCategoryTree] = useState([]);
  const [brandName, setBrandName] = useState<any>("");
  const [imageUrl, setImageUrl] = useState<any>();
  const [categoryRoutId, setCategoryRoutId] = useState<any>("ALL");
  const router = useRouter();

  const slides = [
    { url: "/images/brands/brandCarousel/carousel_Image1.jpg" },
    // { url: "/images/brands/brandCarousel/carousel_Image2.jpg" },
    { url: "/images/brands/brandCarousel/carousel_Image3.jpg" },
    { url: "/images/brands/brandCarousel/carousel_Image4.jpg" },
  ];

  useEffect(() => {
    setIsFiltersLoading(true);

    CategoryAPI.fetchCategory().then((res) => {
      setCategory(res);
      setIsFiltersLoading(false);
    });
    CategoryAPI.fetchCategoryTree().then((res) => {
      setCategoryTree(res.categories);
      setIsFiltersLoading(false);
    });

    const categoryCode = props?.type ? props?.catogoryId : router?.query?.id;
    const searchParams = props?.type ? props?.search : router?.query?.search;
    const sellerId = props?.type ? props?.sellerId : router?.query?.sellerid;
    const brandId = props?.type ? props?.brandId : router?.query?.brandId;
    const name = props?.type ? props.brand : router?.query?.brand;
    const urlImg = props?.type ? props.url : router?.query?.url;

    setBrandName(name);
    setImageUrl(urlImg);

    const __activeFilterES: any = {
      name: "",
      subText: "",
      category_ids: "",
      brands: [],
      attributes: [],
      product_type: 2,
      vendor_id: [],
      price_range: {
        min: 0,
        max: 0,
      },
      from: 0,
      size: 30,
    };

    if (searchParams != "" && searchParams != undefined) {
      __activeFilterES.name = searchParams;
    }

    if (sellerId != "" && sellerId != undefined) {
      __activeFilterES.vendor_id = sellerId;
    }

    if (
      categoryCode != "All" &&
      categoryCode != "ALL" &&
      categoryCode != "" &&
      categoryCode != undefined
    ) {
      __activeFilterES.category_ids = categoryCode;
    }

    if (brandId != "" && brandId !== undefined) {
      __activeFilterES.brands.push(brandId);
      // if((__activeFilterES.brands).indexOf(brandId)){
      //   __activeFilterES.brands.splice((__activeFilterES.brands).indexOf(brandId), 1);
      // }else{
      //   __activeFilterES.brands.push(brandId);
      // }
    }

    fetchProductsES(__activeFilterES);
    setActiveFilterConditions(__activeFilterES);
    setCategoryRoutId(categoryCode);
  }, [router]);

  const fetchProductsES = async (payload: any) => {
    // setIsProductListLoading(true);

    const activeFilterES: any = {
      from: payload.from,
      size: payload.size,
      query: {
        bool: {
          must: [],
          filter: [],
        },
      },
      sort: {},
      filterable_attributes: {},
    };

    activeFilterES.query.bool.filter.push({
      term: { product_type: payload.product_type },
    });

    if (payload.category_ids != "") {
      const _id: number = +payload.category_ids;
      activeFilterES.query.bool.filter.push({
        terms: { category_ids_new: [_id] },
      });
    }

    if (payload.name != "") {
      activeFilterES.query.bool.must.push({
        query_string: {
          fields: ["name", "sku", "brand_label"],
          query: "*" + payload.name + "*",
          //,"type": "phrase_prefix"
        },
      });
    }
    if (payload.subText != "") {
      activeFilterES.query.bool.must.push({
        query_string: {
          fields: ["name", "sku", "brand_label"],
          query: "*" + payload.subText + "*",
          type: "best_fields",
        },
      });
    }

    if (Array.isArray(payload.brands) && payload.brands.length > 0) {
      activeFilterES.query.bool.filter.push({
        terms: { brand: [...payload.brands] },
      });
    }

    if (payload.vendor_id != "") {
      activeFilterES.query.bool.must.push({
        terms: { vendor_id: [payload.vendor_id] },
      });
    }
    if (payload.sort && Object.keys(payload.sort).length > 0) {
      activeFilterES.sort = payload.sort;
    }
    if (payload.price_range.max > 0) {
      activeFilterES.query.bool.must.push({
        range: {
          f_price: {
            gte: payload.price_range.min,
            lte: payload.price_range.max,
          },
        },
      });
    }
    if (
      payload.filterable_attributes &&
      Object.keys(payload.filterable_attributes).length > 0
    ) {
      const _filterable_attributes_keys = Object.keys(
        payload.filterable_attributes
      );
      for (const _attr of _filterable_attributes_keys) {
        activeFilterES.query.bool.filter.push({
          terms: {
            ["filterable_attributes." + _attr]: [
              ...payload.filterable_attributes[_attr],
            ],
          },
        });
        // for(let _attr_key  of payload.filterable_attributes[_attr]){
        //   let __attr_key:number = +_attr_key;
        //   activeFilterES.query.bool.filter.push({
        //       term : { ["filterable_attributes."+_attr] :  __attr_key},
        //   });
        // }
      }
    }
    delete activeFilterES.filterable_attributes;

    const _activeFilterES = {
      q: activeFilterES,
      index: "product_details",
    };

    // handleRouteChangeStart();

    await axios
      .get(ProductAPIs.fetchProductsListES, { params: { ..._activeFilterES } })
      .then((res) => {
        setIsProductListLoading(false);
        handleRouteChangeEnd();
        if (res?.data) {
          const _response = res.data;
          if (_response.hits && _response && _response) {
            setProductES(_response);
          }
        }
      });
  };

  const handleRouteChangeEnd = () => {
    setState((prevState) => ({
      ...prevState,
      isRouteChanging: false,
    }));
  };

  const slickSettings = {
    dots: true,
    arrows: false,
    infinite: true,
    speed: 400,
    slidesToShow: 1,
    slidesToScroll: 1,
    nextArrow: <SampleNextArrow />,
    prevArrow: <SamplePrevArrow />,
    responsive: [
      {
        breakpoint: 1200,
        settings: {
          slidesToShow: 6,
        },
      },
      {
        breakpoint: 767,
        settings: {
          slidesToShow: 3,
          dots: true,
          arrows: false,
        },
      },
    ],
  };

  return (
    <>
       <SEOHead
        title={brandName}
        description={description}
        url={window.location.href} 
        image={imageUrl}
      />
      <MediaQuery minWidth={769}>
        <div
          className={cx(styles.brandBannerDiv)}
          style={{ backgroundColor: "#F5F5F5" }}
        >
          <div className={cx(styles.brandLabelSection)}>
            <img
              src={`${baseUrl}/${router?.query?.url}`}
              alt={"brand-IMG"}
              className={styles.brandImg}
            />
            <div className={styles.sectionText}>
              <span className={styles.sectionTitle}>
                High Performance Composite V-Belts
              </span>
              <span className={styles.sectionSubTitle}>
                Express FAST Delivery
              </span>
            </div>
            <Button type="primary">Explore Brand</Button>
          </div>

          <div className={styles.sliderContainer}>
            <ImageSlider slides={slides} />
          </div>
        </div>
        <BrandLatestOffers products={productsES.hits.hits || []} />
        <BrandFeaturedProducts
          products={productsES.hits.hits || []}
          listMetaData={productsES.hits || {}}
          fetchProducts={fetchProductsES}
          activeFilters={activeFilterConditions}
          setActiveFilters={(data: any) => setActiveFilterConditions(data)}
        />

        {/* <BrandFeaturedCategory /> */}
        {brandName && brandName.toUpperCase() == "BOSCH" ? (
          <BrandStory />
        ) : (
          <></>
        )}
        <BrandVideoCard />
      </MediaQuery>

      <MediaQuery maxWidth={769}>
        <div
          className={cx(styles.brandBannerDiv)}
          style={{ backgroundColor: "#F5F5F5" }}
        >
          <div className={cx(styles.brandLabelSection)}>
            <img
              src={`${baseUrl}/${router?.query?.url}`}
              alt={"brand-IMG"}
              className={styles.brandImg}
            />
            <div className={styles.sectionText}>
              <span className={styles.sectionTitle}>
                High Performance Composite V-Belts
              </span>
              <span className={styles.sectionSubTitle}>
                Express FAST Delivery
              </span>
            </div>
            <Button type="primary">Explore Brand</Button>
          </div>

          <div className={styles.sliderContainer}>
            <ImageSlider slides={slides} />
          </div>
        </div>
        {productsES.hits.hits ? (
          <>
            <BrandLatestOffers products={productsES.hits.hits || []} />
            <BrandFeaturedProducts
              products={productsES.hits.hits || []}
              listMetaData={productsES.hits || {}}
              fetchProducts={fetchProductsES}
              activeFilters={activeFilterConditions}
              setActiveFilters={(data: any) => setActiveFilterConditions(data)}
            />
          </>
        ) : (
          <></>
        )}

        <BrandVideoCard />
      </MediaQuery>
    </>
  );
};

export default brandPage;
