import { FC, useContext, useEffect, useState } from "react";
import Router, { useRouter } from "next/router";

import cx from "classnames";
import styles from "./address.module.scss";

import {
  Form,
  Button,
  Alert,
  Modal,
  Radio,
  Space,
  notification,
  Skeleton,
  Checkbox,
} from "antd";

import AddressCard from "./AddressCard";
import Invoice from "../../Invoice/Invoice";
import * as CartApi from "../../../pages/api/cart";
import * as CommonApi from "../../../pages/api/common";
import * as AddressApi from "../../../pages/api/address";
import AddressModal from "../../modal/addressModal/AddressModal";
import _ from "lodash";
import CustomProgressBar from "../ProgressBar";
import shopConetxt from "../../../context/shopConetxt";
import Loading from "../../Loading";
import { useMediaQuery } from "react-responsive";
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { baseUrl } from "../../../constants/urls";
import { LeftOutlined } from "@ant-design/icons";

const AddressContainer: FC<any> = ({stateArray}) => {
  const { isProductListLoading, setIsProductListLoading } =
    useContext(shopConetxt);
  const [selectedShippingAddressId, setSelectedShippingAddressId] =
    useState("");
  const [selectedBillingAddressId, setSelectedBillingAddressId] = useState("");

  const [productInvoice, setProductInvoice] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [addresses, setAddresses] = useState<any>([]);
  const [loginRes, setLoginRes] = useState<any>({});
  const [shipAddressSelect, setShipAddressSelect] = useState<any>({});
  const [billAddressSelect, setBillAddressSelect] = useState<any>({});
  const [isAddress, setIsAddress] = useState(false);
  const [shipmentSelection, setShipmentSelection] = useState(false);
  const [shipmentRates, setShipmentRates] = useState([]);
  const [listBillingAddress,setListBillingAddress] = useState([]);
  const [shippingRate, setShippingRate] = useState<any>("");
  const [isButtonDisable, setIsButtonDisable] = useState(false);
  const [checked, setChecked] = useState(true);
  const router = useRouter();
  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  });
  useEffect(() => {
    setIsProductListLoading(true);
    handleRouteChangeStart();
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    // console.log(details,"details")
    setLoginRes(details);

    CommonApi.getRequestWithToken(`${baseUrl}/api/customer-address/billing-address?token=true`,details?.token).then((res)=>{
      // console.log(res,"res")
      setListBillingAddress(res?.data?.data);
      if(res?.data?.data.length>0){
      if(details?.data?.company_gst!="" || details?.data?.company_gst !=null){
      setBillAddressSelect(res?.data?.data?.[0]);
      setSelectedBillingAddressId(res?.data?.data?.[0]?.id);
      setChecked(false);
      }
    }
  
    const tokenData: any = !_.isEmpty(details) ? details.token : null;
    CartApi.cartFetch(tokenData).then((cartRes) => {
      if (cartRes.data !== null) {
        setProductInvoice(cartRes.data);
      }
    });

    if (!_.isEmpty(details)) {
      AddressApi.getAdresses(details.token).then((address) => {
        setIsProductListLoading(false);
        handleRouteChangeEnd();
        setAddresses(address?.data);
        const found = address?.data.find(
          (element: any) => element.is_default === true
        );
        if(res?.data?.data.length==0){
        setBillAddressSelect(found);
      setSelectedBillingAddressId(found?.id);
        }
        setSelectedShippingAddressId(found?.id);
        setShipAddressSelect(found);
       
      });
    }
  })
  }, []);

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

  const CloseModal = () => {
    if (!_.isEmpty(loginRes)) {
      AddressApi.getAdresses(loginRes.token).then((address) => {
        setAddresses(address.data);
        setModalVisible(false);
      });
    }
  };

  const selectShipAddress = (addrs: any) => {
    AddressApi.idDefaultAddress(loginRes?.token,addrs.id,loginRes?.data?.id).then((res)=>{});
    setShipAddressSelect(addrs);
    setSelectedShippingAddressId(addrs.id);
  };

  const selectBillAddress = (adds: any) => {
    setBillAddressSelect(adds);
    setSelectedBillingAddressId(adds.id);
  };

  const checkOutAddress = () => {
    handleRouteChangeStart()
    const filteredArray = addresses.filter((obj:any) => obj.address_type !== 'customer_billing_address');

// Get the length of the filtered array
  const lengthOfFilteredArray = filteredArray.length;
// console.log(lengthOfFilteredArray,"lengthOfFilteredArray");
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    if(lengthOfFilteredArray==0){
      notification.error({message:"add shipping address and select it"})
      handleRouteChangeEnd();
    }else
    if (_.isEmpty(billAddressSelect) && _.isEmpty(shipAddressSelect)) {
      handleRouteChangeEnd();
      notification.error({message:"Please add address & not please select address"});
    } else if (!checked && _.isEmpty(billAddressSelect)) {
      handleRouteChangeEnd();
      notification.error({message:"Please Select Billing Address"});
    } else if (_.isEmpty(shipAddressSelect)) {
      handleRouteChangeEnd();
      notification.error({message:"Please add New address or Please Select Shipping Address"});
    } else {
      setIsButtonDisable(true);
      // const ship_address_lab = shipAddressSelect?.address1?.[1]?.split(",");
      // // console.log(shipAddressSelect,"shipAddressSelect");
      
      // const ship_label = ship_address_lab?.splice(ship_address_lab?.length - 2, 2);
      // const finalValue = [ship_address_lab?.toString()];
      // let billing_address_lab;
      // if(checked){
      //  billing_address_lab = billAddressSelect?.address1?.[1]?.split(",");
      // }
      // // console.log(billing_address_lab,"billAddressSelect");
    
      // const bill_label = billing_address_lab?.splice(billing_address_lab?.length - 2, 2);
      // const bill_finalValue = [billing_address_lab?.toString()];
      const params = {
        token: tokenData,
        billing: {
          address1: checked?Object.assign({}, [shipAddressSelect?.address1?.[1]]):loginRes?.data?.company_gst!="" || loginRes?.data?.company_gst !=null?Object.assign({}, [billAddressSelect?.address1+" "+billAddressSelect?.address2]):Object.assign({}, [billAddressSelect?.address1?.[1]]),
          first_name: checked &&loginRes?.data?.company_gst!="" ||  checked && loginRes?.data?.company_gst !=null?shipAddressSelect.first_name:billAddressSelect.first_name,
          last_name: checked &&loginRes?.data?.company_gst!="" ||  checked && loginRes?.data?.company_gst !=null?shipAddressSelect.last_name:billAddressSelect.last_name,
          email: loginRes.data.email,
          address_id: checked &&loginRes?.data?.company_gst!="" ||  checked && loginRes?.data?.company_gst !=null?shipAddressSelect.id:billAddressSelect.id,
        },
        shipping: {
          address1: Object.assign({}, [shipAddressSelect?.address1?.[1]]),
          first_name: shipAddressSelect.first_name,
          last_name: shipAddressSelect.last_name,
          email: loginRes.data.email,
          address_id: shipAddressSelect.id,
        },
      };
     


      CartApi.cartAddressAdd(params).then((resSave) => {
        if (resSave?.data?.rates.length > 0) {
          // setShipmentSelection(true);
          // setShipmentRates(resSave?.data?.rates?.[0]?.rates);
          const shipParams = {
            token: loginRes.token,
            shipping_method: "multiple",
          };

          CartApi.cartShipping1(shipParams).then((shipD) => {
            localStorage.setItem("shipment", JSON.stringify(shipD));
            handleRouteChangeEnd();
            Router.push("/payment");
          });
        } else {
          handleRouteChangeEnd();
          // setIsAddress(true);
          setIsButtonDisable(false);
          notification.error({message:resSave?.message});
        }
        // CartApi.cartShipping1(loginRes.token).then((shipD1)=>{
        //   console.log(shipD1,"shipD1");
        // })
      });
    }
    //  Router.push("/payment")
  };

  const shippingSubmit = () => {
    if (shippingRate === "") {
      notification.error({ message: "Please Select Shipment type" });
    } else {
      const shipParams = {
        token: loginRes.token,
        shipping_method: shippingRate,
      };

      CartApi.cartShipping1(shipParams).then((shipD) => {
        localStorage.setItem("shipment", JSON.stringify(shipD));
        Router.push("/payment");
      });
    }
  };
  const shipMethod = (data: any) => {
    setShippingRate(data.target.value);
  };
  const onChange = (e: CheckboxChangeEvent) => {
    // console.log('checked = ', e.target.checked);
    setChecked(e.target.checked);
  };
  const backRoute = () => {
    router.back();
  }; 
  // console.log(listBillingAddress,"listBillingAddress")
  const isMobileRes = useMediaQuery({ maxWidth: 767.68 });
  return (
    <>
      <Loading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
      <Button
        className={cx("mx-10", styles.buckButton)}
        style={{ fontSize: "20px",cursor:"pointer",alignItems:"center",justifyContent:"center",display:'flex' }}
        type="link"
        onClick={backRoute}
        icon={<LeftOutlined />}
      >
       
        Back
      </Button>
      <div className={cx("pb-12",styles.mainContainer)}>
        <div className={cx("text-center", styles.checkoutPageTitle)}>
          Checkout
        </div>
        <div className={cx("m-auto", styles.progressBar)}>
          <CustomProgressBar progress={50} />
        </div>
        <div
          className={cx(
            "flex p-12 justify-between pb-6",
            styles.checkoutPageContainer
          )}
        >
          <div
            className={cx(
              "flex justify-between p-10",
              styles.checkoutLeftSection
            )}
          >
            <Form className="w-full" layout="vertical">
              <div className="flex justify-between items-center">
                <div className={styles.sectionHeader}>Shipping Address</div>
                <Button
                  className={styles.addAddressButton}
                  type="primary"
                  ghost
                  onClick={() => {
                    setModalVisible(true);
                  }}
                >
                  Add New Address
                </Button>
              </div>
              {isProductListLoading ? (
                  <div>
                    <Skeleton active></Skeleton>
                  </div>
                ) : (
              <div className={cx("mt-2 mb-4", styles.addressContainer)}>
                {addresses.map((address: any, index: number) => (<>
                  {address.address_type!=="customer_billing_address"&&
                      <AddressCard

                        key={index}
                        selectedShippingAddressId={selectedShippingAddressId}
                        selectedBillingAddressId={selectedBillingAddressId}
                        address={address}
                        addressType={"shipping"}
                        selectShipAddress={selectShipAddress}
                      />
                }</>
                    ))}
                
              
              </div>)}
             
              <div>
                <div className="flex justify-between items-center">
                  <div className={styles.sectionHeader}>Billing Address</div>
                  {/* <Button
                    className={styles.addAddressButton}
                    type="primary"
                    ghost
                  >
                    Add New Address
                  </Button> */}
                </div>
               {listBillingAddress.length==0 || loginRes?.data?.company_gst=="" || loginRes?.data?.company_gst ==null ? <Checkbox checked={checked}  onChange={onChange} style={{marginTop:"1rem"}}>
              Same as Shipping address?
        </Checkbox>:null}

                {!checked && loginRes?.data?.company_gst=="" ||  !checked &&  loginRes?.data?.company_gst ==null?<div className={cx("mt-2 mb-4", styles.addressContainer)}>
                  {addresses.map((address: any, index: number) => (
                    <> {address.postcode!=null?
                    <AddressCard
                      key={index}
                      selectedShippingAddressId={selectedShippingAddressId}
                      selectedBillingAddressId={selectedBillingAddressId}
                      address={address}
                      addressType={"billing"}
                      selectBillAddress={selectBillAddress}
                    />:null}
                    </>
                  ))}
                </div>:null}
                {loginRes?.data?.company_gst!="" || loginRes?.data?.company_gst !=null ?<div className={cx("mt-2 mb-4", styles.addressContainer)}>
                  {listBillingAddress.map((address: any, index: number) => (
                      <> {address.postcode!=null?
                    <AddressCard
                      key={index}
                      selectedShippingAddressId={selectedShippingAddressId}
                      selectedBillingAddressId={selectedBillingAddressId}
                      address={address}
                      addressType={"billing"}
                      selectBillAddress={selectBillAddress}
                    />:null}
                    </>
                  ))}
                </div>:null}
              </div>
            </Form>
          </div>

          <div className={styles.paymentSummary}>
            <Invoice details={productInvoice} />
          </div>
        </div>
        {isAddress ? (
          <Alert
            message="Shipping Not Available"
            description="Shipping not Available this Address"
            type="error"
            closable
            onClose={() => {
              setIsAddress(false);
            }}
          />
        ) : null}
        <div className="px-12">
          <Button
          disabled={isButtonDisable}
            onClick={checkOutAddress}
            className={cx("my-4", styles.nextButton)}
            type="primary"
          >
            Continue
          </Button>
        </div>
        <Modal
          visible={shipmentSelection}
          width={isMobileRes?"90%":"30%"}
         
          onOk={() => {
            setShipmentSelection(false);
          }}
          onCancel={() => {
            setShipmentSelection(false);
          }}
          footer={null}
          destroyOnClose={true}
          bodyStyle={{ height: "100%" }}
        >
          <div className={styles.modalContainer}>
            <h2 className={styles.popupTitle}>Shipping Methods</h2>
            <div className={styles.paymentMethodRadioGroup}>
              <Radio.Group
                value={shippingRate}
                onChange={(evt) => shipMethod(evt)}
              >
                {shipmentRates.map((payOpt: any, idx: number) => {
                  return (
                    <Radio
                      className={styles.paymentOption}
                      value={payOpt.method}
                      key={idx}
                    >
                      {payOpt.carrier_title} &nbsp; - {payOpt.formated_price}
                    </Radio>
                  );
                })}
              </Radio.Group>
            </div>
            <Button
              type="primary"
              className="my-8"
              block
              size="large"
              onClick={shippingSubmit}
            >
              Submit
            </Button>
          </div>
        </Modal>

        {/* <Button
          onClick={checkOutAddress}
          className={styles.mobileNextButton}
          type="primary"
        >
          Next
        </Button> */}
        <AddressModal
          modalVisible={modalVisible}
          onCloseAdress={() => {
            CloseModal();
          }}
          stateArray={stateArray}
        />
      </div>
    </>
  );
};

export default AddressContainer;
