import { FC, useContext, useEffect, useState } from "react";
import cx from "classnames";
import MediaQuery from "react-responsive";
import shopConetxt from "../../../context/shopConetxt";
import * as ProductAPIs from "../../../pages/api/products";
import { VIEW_TYPES } from "../../../constants/product";
import { useRouter } from "next/router";
import axios from "axios";
import ProductHeader from "../../products/productHeader";
import Pagination from "../../products/paginationES";
import ShopByBrandHeader from "../../home/findByBrand/shopByBrandHeader/shopByBrandHeader";
import ProductsListES from "../../products/productsList/ProductsListES";
import { Skeleton } from "antd";
import ProductFilters from "../../../components/products/filters";
import EnquiryPage from "../../enquiry/EnquiryPage";
import Loading from "../../Loading";
import * as CommonAPI from "../../../pages/api/common"
import ProductListPreLoader from "./ProductListPreLoader";
import { baseUrl } from "../../../constants/urls";
import OTPModal from "../../modal/otpModal/OTPModal";
import _ from "lodash";
import ProductNotFound from "../../products/productNotFound/ProductNotFound";

const ProductListCommon: FC<any> = (props: any) => {
	let initLoadEffect = true;
	const {
		isProductListLoading,
		setIsProductListLoading,
	} = useContext(shopConetxt);
	const [isDataLoading, setIsDataLoading] = useState(false);
	const [products, setProducts] = useState<any>({ data: {}, meta: {} });
	const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
	const [productsES, setProductES] = useState<any>({
		hits: { total: { value: 0 }, hits: [] },
	});
	const [viewType, setViewType] = useState(VIEW_TYPES.GRID);
	const [initLoad, setInitload] = useState(false);
	const [filterVisible, setFilterVisible] = useState(false);
	const [activeFilterConditions, setActiveFilterConditions] = useState({});
	const [brandName, setBrandName] = useState<any>();
	const [imageUrl, setImageUrl] = useState<any>();
	const [categoryRoutId, setCategoryRoutId] = useState<any>("ALL");
	const [loadPage, setLoadPage] = useState(false);
	const [isGroupKey, setIsGroupKey] = useState(false)
	const [loginRes, setLoginRes] = useState<any>({});
	const [stateArray, setStateArray] = useState([]);
	const router = useRouter();

	const [state, setState] = useState({
		isRouteChanging: false,
		loadingKey: 0,
	});

	useEffect(() => {
		const val: any = localStorage.getItem("loginDetails");
		const loginDetails = JSON.parse(val);
		const cityPincode: any = localStorage.getItem("PinCode");
		// console.log(cityPincode, "cityPincode");

		setLoginRes(loginDetails);
		// console.log(router,"router");
		setStateArray(props?.stateArray)
		const searchParams1 = props?.type ? props?.search : router?.query?.search;
		CommonAPI.getRequest(`${baseUrl}/api/check-groupbykey/${searchParams1}`).then((resData) => {
			setIsGroupKey(resData?.data?.status)
		})

		if (initLoadEffect) {
			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);
			}
			// __activeFilterES.page = 1;
			fetchProductsES(__activeFilterES);
			setActiveFilterConditions(__activeFilterES);
			setCategoryRoutId(categoryCode);
			initLoadEffect = false;

		}

	}, [router]);

	const fetchProductsES = async (payload: any) => {
		// setIsProductListLoading(true);
		const val: any = localStorage.getItem("loginDetails");
		const loginDetails = JSON.parse(val);
		const searchParams1 = props?.type ? props?.search : router?.query?.search;
		const discountRange= router?.query?.pd_rd_d;
		
		CommonAPI.getRequest(`${baseUrl}/api/check-groupbykey/${searchParams1}`).then(async (resData) => {
			// console.log(resData,"resData")

			setIsGroupKey(resData?.data?.status)

			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: any = +payload.category_ids;
				activeFilterES.query.bool.filter.push({
					terms: { category_ids_new: [_id] },
				});
			}

			if (payload.name != "") {
				let variable = {}
				if (resData?.data?.status == true) {
					variable = { "match_phrase": { "groupby_key": { "query": payload.name, "slop": 2 } } }
				} else {
					variable = {
						"multi_match": {
							"query": payload.name,
							"fields": [
								"groupby_key^1000",
								"search_keywords^1000",
								"sku^500",
								"brand_label^500",
								// "name^800",
								// "sku^200",
								// "category_names^100"
							],
							"type": "best_fields",
							"operator": "and",

							"fuzziness": 1





						}
					}
				}
				activeFilterES.query.bool.must.push(variable);
			}
			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.sort.f_price == "asc") {

					activeFilterES.query.bool.must.push({
						range: {
							f_price: {
								gt: "0"
							}
						},
					});
				}

			}


			if(discountRange){
				activeFilterES.query.bool.must.push({
					range: {
						selling_price_discount: {"gte":50,"lte":70}},
					
				});	
				activeFilterES.sort.push({
					"selling_price_discount":"desc"
				})
			}

			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],
							],
						},
					});

				}
			}
			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);
							//console.log(res);
							if (res?.data?.hits?.hits?.length == 0) {
								setLoadPage(true);
								return;
								if (_.isEmpty(loginDetails)) {
									setIsOTPModalVisible(!isOTPModalVisible);
								}else {
									router.push(
										{
											pathname: `/rfq`
										},

									);
								}
							}
							// setLoadPage(true);
						}
					}
				});
		})
	};

	const onViewTypeChange = (viewType: string) => {
		setViewType(viewType);
	};

	const toggleFilterVisible = () => {
		setFilterVisible(!filterVisible);
	};

	const handleRouteChangeStart = () => {

		setState((prevState) => ({
			...prevState,
			isRouteChanging: true,
			loadingKey: prevState.loadingKey ^ 1,
		}));
	};
	const handleRouteChangeEnd = () => {
		if (!initLoad)
			setInitload(true);
		setState((prevState) => ({
			...prevState,
			isRouteChanging: false,
		}));
	};

	return (
		<>
			<Loading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
			<MediaQuery maxWidth={768}>
				{imageUrl ? (
					<ShopByBrandHeader brandName={brandName} brandLogo={imageUrl} />
				) : null}

				{productsES && productsES.hits.hits.length > 0 ? (
					<>
						<ProductHeader
							setViewType={onViewTypeChange}
							productInfo={products.meta}
							activeFilters={activeFilterConditions}
							fetchProducts={fetchProductsES}
							setActiveFilters={(data: any) => setActiveFilterConditions(data)}
						/>
						<ProductFilters
							toggleFilterVisible={toggleFilterVisible}
							fetchProducts={fetchProductsES}
							productsES={productsES}
							filterVisible={filterVisible}
							categoryRoutId={categoryRoutId}
							activeFilters={activeFilterConditions}
							setActiveFilters={(data: any) => setActiveFilterConditions(data)}
						/>
						{isDataLoading ? (
							<div className="flex">
								<Skeleton active></Skeleton>
							</div>
						) : (

							<>
								<ProductsListES
									products={productsES.hits.hits || []}
									viewType={viewType}
									handleRouteChangeStart={handleRouteChangeStart}
									handleRouteChangeEnd={handleRouteChangeEnd}
								/>
								<Pagination
									listMetaData={productsES.hits || {}}
									fetchProducts={fetchProductsES}
									activeFilters={activeFilterConditions}
									setActiveFilters={(data: any) =>
										setActiveFilterConditions(data)
									}
								/>
							</>
						)}</>) : (
					<>{loadPage && <ProductNotFound  stateArray={props?.stateArray}/>}</>
				)}


				{/* {isProductListLoading ? (
          <div className={style.productListLoaderContainer}>
            <Spin indicator={antIcon} />
          </div>
        ) : (
          <>
            <ProductsListES
              products={productsES.hits.hits || []}
              viewType={viewType}
            />

            <Pagination
              listMetaData={productsES.hits || {}}
              fetchProducts={fetchProductsES}
              activeFilters={activeFilterConditions}
              setActiveFilters={(data: any) => setActiveFilterConditions(data)}
            />
          </>
        )} */}
			</MediaQuery>
			<MediaQuery minWidth={769}>
				{<div className={cx("mb-6 mt-3 mx-4 flex")}>
					<ProductFilters
						toggleFilterVisible={toggleFilterVisible}
						fetchProducts={fetchProductsES}
						productsES={productsES}
						filterVisible={filterVisible}
						categoryRoutId={categoryRoutId}
						activeFilters={activeFilterConditions}
						type={props?.type}
						imageUrl={imageUrl}
						setActiveFilters={(data: any) => setActiveFilterConditions(data)}
					/>
					<div className="w-full">
						{imageUrl ? (
							<ShopByBrandHeader brandName={brandName} brandLogo={imageUrl} />
						) : null}

						{productsES && productsES.hits.hits.length > 0 ? (
							<>
								<ProductHeader
									setViewType={onViewTypeChange}
									viewType={viewType}
									productInfo={products.meta}
									activeFilters={activeFilterConditions}
									fetchProducts={fetchProductsES}
									setActiveFilters={(data: any) => setActiveFilterConditions(data)}
								/>
								{isDataLoading ? (
									<div className="flex">
										<Skeleton active></Skeleton>
									</div>
								) : (
									<>
										<ProductsListES
											products={productsES.hits.hits || []}
											viewType={viewType}
										/>
										<Pagination
											listMetaData={productsES.hits || {}}
											fetchProducts={fetchProductsES}
											activeFilters={activeFilterConditions}
											setActiveFilters={(data: any) =>
												setActiveFilterConditions(data)
											}
										/>
									</>
								)} </>) : (
							<>{loadPage && <ProductNotFound stateArray={props?.stateArray} product={router}/>}</>
						)}
					</div>
				</div>}
			</MediaQuery>
			<OTPModal
				page={"productList"}
				stateArray={props?.stateArray}
				handleOTPClose={() => {
					setIsOTPModalVisible(false);
				}}
				isOTPModalVisible={isOTPModalVisible}
			/>
		</>
	);
};

export default ProductListCommon;
