import React, { FC, useContext, useEffect, useState } from "react";

import ProductDetails from "./components/ProductDetails";
import BulkQuantityDiscount from "../coommons/BulkQuantityDiscount";
import CheckAvailability from "../leftPane/components/CheckAvailability";
import DeliveryDetail from "../rightPane/components/DeliveryDetails";
import ProductOffers from "../leftPane/components/ProductOffers";
import ProductDescription from "./components/ProductDescription";
import Assurances from "./components/Assurances";
import Label from "../../common/label";
import styles from "../leftPane/leftPane.module.scss";
import cx from "classnames";
import * as CheckAPI from "../../../pages/api/ship";
import * as CommonApi from "../../../pages/api/common";
import * as AddToCardApi from "../../../pages/api/addTocart";
import * as ShipApi from "../../../pages/api/ship";
import * as CartApi from "../../../pages/api/cart";
import PincodeModal from "../../modal/pincode/PincodeModal";
import shopConetxt from "../../../context/shopConetxt";
import _, { get, isEmpty } from "lodash";
import { useRouter } from "next/router";
import { APIKEY, baseUrl } from "../../../constants/urls";
import {
	FilePdfOutlined,
	CheckCircleFilled,
	WarningFilled,
} from "@ant-design/icons";
import { Image, notification, Radio, Space } from "antd";
import moment from "moment";
import OTPModal from "../../modal/otpModal/OTPModal";
import Geocode from "react-geocode";
import Breadcrumbs from "../../products/productHeader/Breadcrumbs";

const ProductDetailsMobile: FC<any> = ({
	productDetails,
	onBuyNowClick,
	onBulkDiscountSelect,
	requestCallback,
	productAdditionalInfo,
	stateArray,
	attrabuteSelection,
	configurableProducts,
	addToBulkQuentity
}) => {
	const router = useRouter();
	const {
		setDeliveryPriceDetails,
		deliveryPriceDetails,
		deliveryOptions,
		deliveryDunzoPriceDetails,
		setDeliveryDunzoPriceDetails,
		productQuantity,
		setProductQuantity,
	} = useContext<any>(shopConetxt);
	const [isProductOfferModalOpen, setIsProductOfferModalOpen] = useState(false);
	const [isOpenPincode, setIsOpenPincode] = useState(false);
	const [pincode, setPincode] = useState("");
	const [city, setCity] = useState("Hyderabad");
	const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
	const [loginRes, setLoginRes] = useState<any>({});
	const [applyPincode, SetApplyPincode] = useState("");
	const [pincodeData, setPincodeData] = useState<any>([]);
	const [isAddressVisible, setIsAddressVisible] = useState(false);
	const [newSelect, setNewSelect] = useState("");
	const [availability, setAvailabiity] = useState<any>({});
	const cityPincode = localStorage.getItem("PinCode");
	const [selectedDeliveryDetails, setSelectedDeliveryDetails] = useState(0);
	const [deliverypriceDetails, setDeliverypriceDetails] = useState<any>({});
	const [currentAddress, setCurrentAddress] = useState<any>({});
	const [latitude, setLatitude] = useState(null);
	const [longitude, setLongitude] = useState(null);

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

		setLoginRes(loginDetails);
		if (!_.isEmpty(productDetails)) {
			CheckAPI.shippingAvailableCheckingAPI(
				loginDetails?.token,
				productDetails?.inventory_details?.pincode,
				cityPincode,
				productDetails.weight * productDetails?.moq
			).then((res) => {
				setDeliveryPriceDetails(res);
				// console.log(res, "res");
				setAvailabiity(res);
				localStorage.setItem("DeliveryDetails", JSON.stringify(res));
			});
		}

		if (!loginDetails?.data) {
			if (cityPincode !== null) {
				Geocode.setApiKey(APIKEY);
				Geocode.enableDebug();
				Geocode.fromAddress(cityPincode).then(({ results }) => {
					const { lat, lng } = results[0].geometry.location;
					setLatitude(lat);
					setLongitude(lng);
				});
			}
		}
		CommonApi.getRequestWithToken(
			`${baseUrl}/api/customer-pincodes/get-data?token=true&customer_id=${loginDetails?.data?.id}`,
			loginDetails?.token
		).then((Selectres) => {
			setCurrentAddress(Selectres?.data?.data);
		});
	}, [productDetails]);


	const handleOk = () => {
		setIsOpenPincode(false);
	};

	const handleCancel = () => {
		setIsOpenPincode(false);
	};

	const applyNewPincode = () => {
		setIsOpenPincode(false);
	};

	const handlePincodeChange = () => {
		if (pincode.length === 6) {
			SetApplyPincode(pincode);
			localStorage.setItem("city", "Hyderabad");
			localStorage.setItem("PinCode", pincode);
			applyNewPincode();
			if (!isEmpty(loginRes)) {
				const data = {
					id: 0,
					postcode: pincode,
				};
				addressSelect(data);
			}
		} else {
			notification.error({ message: "Please Enter Valid Pin" });
		}
	};

	const addressSelect = (data: any) => {
		console.log(data, "data");

		setNewSelect(data.postcode);
		const params = {
			address_id: data.id,
			pincode: data.postcode,
			customer_id: loginRes?.data?.id,
			ip_address: "",
		};
		CommonApi.postRequestWithToken(
			`${baseUrl}/api/customer-pincodes/create?token=true`,
			params,
			loginRes?.token
		).then((res) => {
			localStorage.setItem("PinCode", res?.data?.data?.pincode);
			SetApplyPincode(res?.data?.data?.pincode);
			setCity(res?.data?.data?.city);
			localStorage.setItem("Citycode", res?.data?.data?.city);
			setIsAddressVisible(false);
			applyNewPincode();
			setPincode("");
			if (router.route === "/products/details/[id]") {
				router.reload();
			}
		});
	};

	useEffect(() => {
		setDeliverypriceDetails(deliveryPriceDetails);
	}, [deliveryPriceDetails]);

	const onChange = (event: any) => {
		setSelectedDeliveryDetails(event.target.value);

		const cityPincode = localStorage.getItem("PinCode");
		setSelectedDeliveryDetails(event.target.value);
		const lat = loginRes?.data ? currentAddress?.latitude : latitude;
		const long = loginRes?.data ? currentAddress?.longitude : longitude;
		if (event.target.value == 1) {
			CommonApi.getRequest(
				`${baseUrl}/api/dunzo/availability?pickup_lat=${productDetails?.inventory_details?.latitude}&pickup_lng=${productDetails?.inventory_details?.longitude}&drop_lat=${lat}&drop_lng=${long}`
			).then((available) => {
				setDeliveryDunzoPriceDetails(available?.data);
				setDeliveryPriceDetails({});
			});
		} else if (event.target.value == 2) {
			setDeliveryPriceDetails({});
			setDeliveryDunzoPriceDetails({});
		} else {
			CheckAPI.shippingAvailableCheckingAPI(
				loginRes?.token,
				productDetails?.inventory_details?.pincode,
				cityPincode,
				productDetails?.weight * productDetails?.moq
			).then((res) => {
				setDeliveryPriceDetails(res);
				setDeliveryDunzoPriceDetails({});
				localStorage.setItem("DeliveryDetails", JSON.stringify(res));
			});
		}
	};
	const dateConver = (days: any) => {
		console.log(days, "days");

		const date = moment();
		return date.day(parseInt(days)).format("DD-MM-YYYY");
	};

	const addToCartSubmit = (details: any) => {
		setProductQuantity({
			id: details.id,
			quantity: get(productQuantity, [details.id], details.moq),
		});
		const pin = localStorage.getItem("PinCode");
		if (pin) {
			if (productDetails.inventories > 0) {
				if (deliveryPriceDetails?.status || deliveryDunzoPriceDetails?.status) {
					const cityPincode = localStorage.getItem("PinCode");
					ShipApi.shippingAvailableCheckingAPI(
						loginRes?.token,
						details.inventory_pincode,
						pin,
						details.weight
					).then((res) => {
						const days =
							deliveryDunzoPriceDetails?.estimated_delivery_mins === undefined
								? deliveryDunzoPriceDetails?.estimated_delivery_mins
								: deliveryDunzoPriceDetails?.estimated_delivery_mins;
						const lat = loginRes?.data ? currentAddress?.latitude : latitude;
						const long = loginRes?.data ? currentAddress?.longitude : longitude;
						setProductQuantity({
							id: details.id,
							quantity: get(productQuantity, [details.id], details.moq),
						});
						const params = {
							product_id: details.id,
							quantity: get(productQuantity, [details.id], details.moq),
							token: loginRes?.token,
							vendor_id: details.vendor_id,
							mp_seller_id: details.mp_seller_id,
							shipping_type: details.id==368707 || details.id==368706 || details.id==368708 || details.id==368709 ? 2:selectedDeliveryDetails,
							estimated_delivery_days: days,
							seller_lat: productDetails?.inventory_details?.latitude,
							seller_lang: productDetails?.inventory_details?.longitude,
							customer_lat: lat,
							customer_lang: long,
							gst:productDetails?.gst,
							customer_pincode: cityPincode,
							seller_pincode: productDetails?.inventory_details?.pincode,
							item_weight: productDetails?.weight,
							shipCharge:details.id==368707 || details.id==368706 || details.id==368708 || details.id==368709 ?0:
								selectedDeliveryDetails == 0
									? deliveryPriceDetails?.rate
									: selectedDeliveryDetails == 2 ? 0 : deliveryDunzoPriceDetails?.rate,
						};

						AddToCardApi.addToCart(params).then((res) => {
							if (res?.message) {
								notification.open({
									message: res?.message,
									duration: 1,
								});
							} else {
								notification.error({
									message: res?.error,
									duration: 1,
								});
							}
							const tokenData: any = !isEmpty(loginRes)
								? loginRes.token
								: null;
							CartApi.cartFetch(tokenData).then((cartRes) => {
								// if (cartRes.data !== null) {
								//   setCartItems(cartRes.data);
								//   setProductInvoice(cartRes.data);
								// }
							});
						});
					});
				} else {
					notification.error({
						message: "Delivery Not Available This Address",
					});
				}
			} else {
				notification.error({ message: "Stock Not available" });
			}
		} else {
			notification.error({ message: "Please Select Location" });
		}
	};

	const handleBuyNowClick = (product: any) => {
		if (deliveryPriceDetails?.status || deliveryDunzoPriceDetails?.status) {
			const cityPincode = localStorage.getItem("PinCode");
			if (cityPincode) {
				const tokenData: any = !isEmpty(loginRes) ? loginRes.token : null;
				const days =
					deliveryDunzoPriceDetails?.estimated_delivery_mins === undefined
						? deliveryDunzoPriceDetails?.estimated_delivery_mins
						: deliveryDunzoPriceDetails?.estimated_delivery_mins;
				const lat = loginRes?.data ? currentAddress?.latitude : latitude;
				const long = loginRes?.data ? currentAddress?.longitude : longitude;
				const params = {
					product_id: product.id,
					quantity: get(productQuantity, [product.id], product.moq),
					token: tokenData,
					mp_seller_id: product.mp_seller_id,
					vendor_id: product.vendor_id,
					shipping_type: product.id==368707 || product.id==368706 || product.id==368708 || product.id==368709 ? 2:selectedDeliveryDetails,
					delivery_time: days,
					seller_lat: productDetails?.inventory_details?.latitude,
					seller_lang: productDetails?.inventory_details?.longitude,
					customer_lat: lat,
					customer_lang: long,
					customer_pincode: cityPincode,
					gst:productDetails?.gst,
					seller_pincode: productDetails?.inventory_details?.pincode,
					item_weight: productDetails?.weight,
					shipCharge:product.id==368707 || product.id==368706 || product.id==368708 || product.id==368709 ?0:
						selectedDeliveryDetails == 0
							? deliveryPriceDetails?.rate
							: selectedDeliveryDetails == 2 ? 0 : deliveryDunzoPriceDetails?.rate,
				};
				AddToCardApi.addToCart(params).then((res) => {
					if (res?.message) {
						notification.open({
							message: res?.message,
							duration: 1,
						});
						CartApi.cartFetch(tokenData).then((cartRes) => {
							// setIsCartLoading(false);
							if (cartRes.data !== null) {
								// setProductInvoice(cartRes.data);
								// setCartItems(cartRes.data);
								router.push("/cart");
							}
						});
					} else {
						notification.error({
							message: res?.error,
							duration: 1,
						});
					}
				});
			} else {
				notification.error({ message: "Please Select Location" });
			}
		} else {
			notification.error({ message: "Delivery Not Available This Address" });
		}
	};

	return (
		<div className="pb-20 mt-24 mx-4">
			<Breadcrumbs />
			<ProductDetails
				productDetails={productDetails}
				onBuyNowClick={handleBuyNowClick}
				addToCart={addToCartSubmit}
				attrabuteSelection={attrabuteSelection}
				configurableProducts={configurableProducts}
			/>
			<BulkQuantityDiscount
				onBulkDiscountSelect={onBulkDiscountSelect}
				bulkQuantityDiscount={productDetails?.bulk_orders}
				addToBulkQuentity={addToBulkQuentity}
				isMobile
			/>
			<div className={styles.pincodeContainer}>
				{/* {deliveryPriceDetails?.status || deliveryDunzoPriceDetails?.status || isEmpty(deliveryPriceDetails) && isEmpty(deliveryDunzoPriceDetails) ? (
					<CheckCircleFilled style={{ color: "#7CAA60" }} />
				) : (
					<WarningFilled style={{ color: "#f00" }} />
				)}
				<span className={styles.availableText}>
					Delivery{" "}
					{deliveryPriceDetails?.status || deliveryDunzoPriceDetails?.status
						? null
						: "on Request"}{" "}
					available at{" "}
					<span
						className={styles.pincodeText}
						onClick={() => {
							setIsOpenPincode(true);
						}}
					>
						{cityPincode}
					</span>
				</span> */}
				{/* {availability.is_available ? (
          <CheckCircleFilled style={{ color: "#7CAA60" }} />
        ) : (
          <WarningFilled style={{ color: "#f00" }} />
        )}
        <span className={styles.availableText}>
          Delivery {availability.status ? null : "Not"} available at{" "}
          <span
            className={styles.pincodeText}
            onClick={() => {
              setIsOpenPincode(true);
            }}
          >
            {cityPincode}
          </span>
        </span> */}
			</div>
			{/* <CheckAvailability isMobile productDetails={productDetails} /> */}
			{/* <div
				className={cx(
					"h-44 bg-white rounded-md",
					styles.deliveryDetailsWrapper
				)}
			>
				<Radio.Group onChange={onChange} value={productDetails?.id==368707 || productDetails?.id==368706 || productDetails?.id==368708 || productDetails?.id==368709?  2: selectedDeliveryDetails} style={{ width: "100%" }} disabled={productDetails?.id==368707 || productDetails?.id==368706 || productDetails?.id==368708 || productDetails?.id==368709?true:false}>
					<Space direction="vertical" style={{ width: "98%" }}>
						{deliveryOptions &&
							deliveryOptions.map((deliveryDetails: any, index: number) => (
								<Radio key={index} value={index} className={index == 0 ? styles.regular : index == 1 ? styles.light : styles.indispare}>
									<div className="flex justify-between" style={{ marginLeft: index == 1 ? "-8px" : 0 }}>
										<div className={styles.deliveryDetails} >
											{deliveryDetails?.label}
											{index == 1 && <><br /><div className={styles.subText}>(Within in 24 Hours)</div></>}
										</div>
										<div className="flex justify-end" style={{ width: "0" }}>
											{index == 1 && <Image src={"/images/details/Group.svg"} preview={false} className={styles.dataSheetBtnIcon} />}
										</div>
									</div>
									
								</Radio>
							))}
					</Space>
					
				</Radio.Group>
			</div> */}
			{/* <DeliveryDetail deliveryDetails={productDetails?.deliveryDetails || {}} /> */}
			{/* <Label
        onClick={() => setIsProductOfferModalOpen(!isProductOfferModalOpen)}
       className={styles.viewMoreOffers}
        lightGray
        label={"View all Offers"}
      /> */}
			{isProductOfferModalOpen ? (
				<ProductOffers
					productDetails={productDetails}
					handleClose={() => setIsProductOfferModalOpen(false)}
				/>
			) : null}
			<ProductDescription
				productDescription={productDetails.description}
				requestCallback={requestCallback}
				userReviews={productDetails?.reviews?.all_reviews}
				faqs={productDetails?.faqs}
				productDetails={productDetails}
				technicalSpecifications={productAdditionalInfo}
			/>
			<Assurances assurances={productDetails?.assurances} />
			{isOpenPincode ? (
				<PincodeModal
					isOpen={isOpenPincode}
					handleOk={handleOk}
					handleCancel={handleCancel}
					handlePincodeChange={handlePincodeChange}
					addressSelect={addressSelect}
					SetApplyPincode={SetApplyPincode}
					pincode={pincode}
					setPincode={setPincode}
					applyPincode={applyPincode}
					newSelect={newSelect}
					setNewSelect={setNewSelect}
					isOTPModalVisible={isOTPModalVisible}
					setIsOTPModalVisible={setIsOTPModalVisible}
				/>
			) : null}
			<OTPModal
				handleOTPClose={() => {
					setIsOTPModalVisible(false);
				}}
				isOTPModalVisible={isOTPModalVisible}
				stateArray={stateArray}
			/>
		</div>
	);
};

export default ProductDetailsMobile;
