import { Button, Card, Image, notification } from "antd";
import styles from "./addressBook.module.scss";
import cx from "classnames";
import { shippingaddress } from "../../../mockData/addresses";
import { FC, useEffect, useState } from "react";

import AddressModal from "../../modal/addressModal/AddressModal";
import * as AddressApi from "../../../pages/api/address";
import* as CommonApi from "../../../pages/api/common";
import AddressCard from "../../CheckoutPage/address/AddressCard";
import EditAddressModal from "../../modal/editAddressModal/EditAddressModal";
import Loading from "../../Loading";
import { baseUrl } from "../../../constants/urls";

const AddressBookCards: FC<any> = ({stateArray}) => {
  const [addressData, setAddressData] = useState<any>([]);
  const [isNewAddress, setIsNewAddress] = useState(false);
  const [isEditAddress, setIsEditAddress] = useState(false);
  const [loginRes, setLoginRes] = useState<any>({});
  const [editDetail,setEditDetails]=useState<any>({});
  const [id,setId]=useState(0);
  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  });

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

  useEffect(() => {
    getAddress();
   
  }, []);
  

  const getAddress=()=>{
    handleRouteChangeStart();
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    setLoginRes(details);
    const token = details?.token;
    AddressApi.getAdresses(token).then((res) => {
      if(res?.data?.length==1){
        if(res?.data?.[0]?.address_type!="customer_billing_address"){
        defaultSubmit(res?.data?.[0],details);
        const params = {
          address_id: res?.data?.[0].id,
          pincode: res?.data?.[0].postcode,
          customer_id: details?.data?.id,
          ip_address: "",
        };
        CommonApi.postRequestWithToken(
          `${baseUrl}/api/customer-pincodes/create?token=true`,
          params,
          token
        ).then((resR) => {
          localStorage.setItem("PinCode", resR?.data?.data?.pincode);
          
          localStorage.setItem("Citycode", resR?.data?.data?.city);
      })
    }
  }
      handleRouteChangeEnd();
      setAddressData(res.data)});
  }

  const EditAddress = (details: any) => {
    setId(details.id);
    setIsEditAddress(true);
    return;
    
   
  };
  const deteleAddress=(details: any)=>{
    handleRouteChangeStart();
    const params={
      id:details.id,
      token:loginRes?.token
    }
    AddressApi.addressDeleteID(params).then((res)=>{
      
      notification.success({message:"Address Deleted Successfully"});
      getAddress();
      handleRouteChangeEnd();
     
    })
  }

  const newAddressHandler = () => {
    setIsNewAddress(true);
  };
  const closeModal = () => {
    getAddress();
    setIsNewAddress(false);
  };

  const defaultSubmit=(address:any,login:any)=>{
    handleRouteChangeStart();
AddressApi.idDefaultAddress(login?.token,address.id,login?.data?.id).then((res)=>{
  console.log(res,"res");
  // getAddress();
  AddressApi.getAdresses(login?.token).then((res) => {
    setAddressData(res.data)
  });
  });


  }


  return (
    <>
    <div className={styles.addressbookContainer}>
    <Loading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
    <div >
      <div className={cx(styles.headerContainer, "ant-row")}>
        <h1 className={cx(styles.cardHeader, "ant-col-xl-20 ant-col-xs-12 ")}>
          Address Book
        </h1>
        {/* <Button
          className={cx("ant-col-xl-4 ant-col-sm-10 ant-col-xs-12")}
          type="primary"
          onClick={newAddressHandler}
        >
          Add New Address{" "}
        </Button> */}
      </div>
       <Card
        title="Your Addresses"
        headStyle={{
          fontSize: "16px",
          fontWeight: "600",
          lineHeight: "22px",
          letterSpacing: "0px",
          border:0
        }}
        className={styles.cardContainer}
        extra={
          <a href="#">
            <Button type="primary" onClick={newAddressHandler}>
              Add New Address{" "}
            </Button>
          </a>
        }
      >
        <div className="ant-row">
          {addressData?.length == 0 ? (
            <div> Please Add Address</div>
          ) : (
            addressData?.map((address: any, index: number) => {
             
              return (
                <>
                 {address.postcode!=null?<div className="ant-col-xl-12 ant-col-xs-24 mb-6" key={index}>
                 <Card
                    title={ address.company_name !=null && address.company_name !=""?address.company_name:address.first_name + " " + address.last_name}
                    className={cx(styles.customCardStyle)}
                    bodyStyle={{ padding: "0 12px  !important" }}
                    headStyle={{ height: "40px" }}
                    extra={<>
                      {address.address_type!="customer_billing_address" ?
                      <div>
                            <div
                          className={styles.extraButtons}
                          onClick={() => {
                            EditAddress(address);
                          }}
                        >
                          <Image
                            src="/images/editcard.svg"
                            width="35px"
                            height="35px"
                            preview={false}
                          />
                        </div>{" "}
                        <div className={styles.extraButtons}  onClick={() => {
                            deteleAddress(address);
                          }}>
                          <Image
                            src="/images/deletecard.svg"
                            width="35px"
                            height="35px"
                            preview={false}
                          />
                        </div>{" "}
                    
                      </div>:null}
                      </>
                    }
                  >
                  
                    <span className={styles.addressText}>{address.address1.toString()}</span><br/>
                    <span className={styles.addressText}>{address.city}</span><br/>
                    <span className={styles.addressText}>{address.state}</span><br/>
                    <span className={styles.addressText}>{address.postcode}</span><br/>
                    <span className={styles.addressText}>{address.phone}</span><br/>
                    <>{address.address_type!="customer_billing_address"?<div/>:
                    address.address_type!="customer_billing_address"&&address.is_default?<Button style={{ margin: "1rem 0" }} type="primary" ghost disabled>
                       default
                    </Button>:<Button style={{ margin: "1rem 0" }} type="primary" ghost onClick={()=>{defaultSubmit(address,loginRes)}}>
                      Set default
                    </Button>}
                    </>
                  </Card>
                </div>:null}
                </>
              );
            })
          )}
        </div>
      </Card>
      {/* <Card
        title="Billing Address"
        headStyle={{
          fontSize: "16px",
          fontWeight: "600",
          lineHeight: "22px",
          letterSpacing: "0px",
          border:0
        }}
        className={styles.cardContainer}
        // extra={
        //   <a href="#">
        //     <Button type="primary" onClick={newAddressHandler}>
        //       Add New Address{" "}
        //     </Button>
        //   </a>
        // }
      >
        <div className="ant-row ">
          {addressData.map((address: any, index: number) => {
            return (
              <div className="ant-col-xl-12 ant-col-xs-24 mb-6" key={index}>
                <Card
                  bodyStyle={{ padding: "12px 24px" }}
                  headStyle={{ height: "40px" }}
                  title={address.first_name}
                  className={cx(styles.customCardStyle)}
                  // extra={
                  //   <div>
                  //     <div className={styles.extraButtons}>
                  //       <Image
                  //         src="/images/deletecard.svg"
                  //         width="35px"
                  //         height="35px"
                  //         preview={false}
                  //       />
                  //     </div>{" "}
                  //     <div className={styles.extraButtons}>
                  //       <Image
                  //         src="/images/editcard.svg"
                  //         width="35px"
                  //         height="35px"
                  //         preview={false}
                  //       />
                  //     </div>{" "}
                  //   </div>
                  // }
                >
                    <span className={styles.addressText}>{address.address1.toString()}</span><br/>
                    <span className={styles.addressText}>{address.city}</span><br/>
                    <span className={styles.addressText}>{address.state}</span><br/>
                    <span className={styles.addressText}>{address.postcode}</span><br/>
                    <span className={styles.addressText}>{address.phone}</span><br/>
                  {/* <Button style={{ margin: "1rem 0" }} type="primary" ghost>
                    Set default
                  </Button> 
                </Card>
              </div>
            );
          })}
        </div>
      </Card> */}

      {isNewAddress&&<AddressModal modalVisible={isNewAddress} onCloseAdress={closeModal}  stateArray={stateArray}/>}
     {isEditAddress && <EditAddressModal
        modalVisible={isEditAddress}
        onCloseAdress={() => {
          setIsEditAddress(false);
          getAddress();
        }}
        id={id}
      />}
    </div>
    </div>
   </>
  );
};

export default AddressBookCards;
