MYADDRESSAKA

mail@pastecode.io avatar
unknown
plain_text
6 months ago
59 kB
3
Indexable
Never
import React, { useState, useEffect } from 'react';
import 'firebase/auth';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
// import Link from 'next/link';
import { Modal, Button, Form } from 'react-bootstrap';
import axios from 'axios';
import Header from 'no/components/buildingBlocks/Header';
import Footer from 'no/components/buildingBlocks/Footer';
// import Image from 'next/image';
// import payment_img from '../../assets/thank_you101.png';
// import cancelimg from '../../assets/cancel.png';
// import { toast } from 'react-toastify';
import { useRouter } from 'next/router';
import { setUserDetails } from 'no/redux/slices/UserSlice';
// import { setAmountDetails } from 'no/redux/slices/amountSlice';
import { useDispatch, useSelector } from 'react-redux';
// import { CartSliceData } from 'no/redux/slices/CartSlice';
// import { deleteUserAddress } from 'no/redux/slices/UserSlice';
// import { setUserDetails } from 'no/redux/slices/UserSlice';


import { Container, Row, Col } from 'react-bootstrap';
import Nav from 'react-bootstrap/Nav';
import Link from 'next/link';



function ShoppingCart() {
  const router = useRouter();
  const [showReviewModal, setReviewShowModal] = useState(false);
  const dispatch = useDispatch();

  const userSliceData: any = useSelector<any>((state) => state?.user);

  //   const amountSliceData: any = useSelector<any>((state) => state?.amount);

  const [states, setStates] = useState([]);

  const [selectedState, setSelectedState] = useState<any>('');


  const shippingAddressOption = userSliceData?.address?.filter(
    (item: any) => item?.type === 'shipping'
  );
  const billingAddressOption = userSliceData?.address?.filter(
    (item: any) => item?.type === 'billing'
  );



  const [charges, setCharges] = useState();

  const [headerKey, setHeaderKey] = useState(0);






  console.log(
    '🚀 ~ file: index.tsx:27 ~ ShoppingCart ~ userSliceData:',
    userSliceData
  );



  const [cardData, setCardData] = useState([]);

  const [quantities, setQuantities] = useState<number[]>([]);

  const [activeStep, setActiveStep] = useState(0);

  const [token, setToken] = useState('');
  console.log(token, 'token');

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [carts, setCarts] = useState(null);
  console.log(setCarts)
  console.log('🚀 ~ file: index.tsx:50 ~ ShoppingCart ~ carts:', carts);


  const addressDeliveryData = localStorage.getItem('addressDeliveryData');
  const parsedAddressUser = addressDeliveryData && addressDeliveryData !== 'undefined' ? JSON.parse(addressDeliveryData) : null;
  const [addressUser, setAddressUser] = useState<any>(parsedAddressUser);

  const billingAddressData = localStorage.getItem('billingAddressData');
  const parsedBillingAddress = billingAddressData && billingAddressData !== 'undefined' ? JSON.parse(billingAddressData) : null;

  const [billingAddress, setBillingAddress] =
    useState<any>(parsedBillingAddress);

  const [useDeliveryAddress, setUseDeliveryAddress] = useState(false);
  const [addresserName, setAddresserName] = useState(null);




  console.log(addresserName, 'h');

  const [paymentMethod, setPaymentMethod] = useState('BANKWIRE_TRANSFER');
  const [orderData, setOrderData] = useState();
  console.log(orderData, 'o');

  // const [addressContact,setAddressContact]=useState()

  const [emailError, setEmailError] = useState('');
  const [passwordError, setPasswordError] = useState('');





  const [formErrors, setFormErrors] = useState<any>({});

  const [addressData, setAddressData] = useState<any>({
    type: 'shipping',
    zip: '',
    city: '',
    state: '',
    country: '',
    street_address: '',
    firstName: '',
    title: '',
    lastName: '',
    contactNumber: '',
    company: ''
  });

  console.log(addressData, "this is addressData")

  //   const handleAddressChange = (event: any) => {
  //     const { name, value } = event.target;
  //     if (name === 'type') {
  //       setAddressData((prevState: any) => ({
  //         ...prevState,
  //         type: value,
  //       }));
  //     } else {
  //       const updatedAddressData = { ...addressData };
  //       updatedAddressData[name] = value;
  //       setAddressData(updatedAddressData);
  //     }

  //     if (name === 'country') {
  //       const selectedCountry:any = filteredCountries.find(
  //         (country: any) => country.name === value
  //       );
  //       if (selectedCountry) {
  //         fetchStates(selectedCountry.id);

  //         setAddressData((prevState: any) => ({
  //           ...prevState,
  //           state: '',
  //         }));
  //         setSelectedState('');
  //         console.log(addressData?.state,"addressData?.state")
  //       } else {
  //         setStates([]);
  //         setSelectedState('');
  //         console.log(addressData?.state,"addressData?.state")

  //       }
  //     }

  //     console.log(addressData.state,"mya")
  //     setSelectedState(selectedState);
  //   };

  const handleAddressChange = (event: any) => {
    const { name, value } = event.target;
    console.log("checkaddress", name, value)
   
    if (name === 'type') {
      setAddressData((prevState: any) => ({
        ...prevState,
     
        type: value
      }))  ;
    } else {
      const updatedAddressData = { ...addressData };
      updatedAddressData[name] = value;
      setAddressData(updatedAddressData);
    }
   
    if (name === 'country') {
      const selectedCountry: any = filteredCountries.find(
        (country: any) => country.name === value
      );
      if (selectedCountry) {
        fetchStates(selectedCountry.id);
        setAddressData((prevState: any) => ({
          ...prevState,
          state: '',
        }));
        setSelectedState('');
      } else {
        setStates([]);
        setAddressData((prevState: any) => ({
          ...prevState,
          state: '',
        }));
        setSelectedState('');
      }
    } 
  };

  useEffect(() => {
    if (addressData?.state && states.some((state: any) => state.name === addressData.state)) {
      console.log(addressData?.state, 'addy')
      setSelectedState(addressData.state);
    } else {
      setSelectedState('');
    }
  }, [addressData?.state, states]);



















  const handleAddressSubmit = async (event: any, token: any) => {
    event.preventDefault();
   
    const authToken = token || userSliceData?.token;

    console.log(authToken, "dma")


    if (addressData?.id) {


      setFormErrors({});

      let errors = {};
      if (!addressData?.firstName) {
        errors = { ...errors, firstName: 'First Name is required' };
      }
    /*   if (!addressData?.lastName) {
        errors = { ...errors, lastName: 'Last Name is required' };
      } */
      // if (!addressData?.company) {
      //   errors = { ...errors, company: 'Company Name is required' };
      // }
      if (!addressData?.street_address) {
        errors = { ...errors, street_address: 'Address is required' };
      }
      if (!addressData?.country) {
        errors = { ...errors, country: 'Country Name is required' };
      }
      if (!addressData?.city) {
        errors = { ...errors, city: 'City Name is required' };
      }
      if (!addressData?.zip) {
        errors = { ...errors, zip: 'Zip Code is required' };
      }
      if (!addressData?.title) {
        errors = { ...errors, title: 'Alias is required' };
      }
      if (!addressData?.contactNumber) {
        errors = { ...errors, contactNumber: 'Contact No. is required' };
      }


      const selectedCountry: any = filteredCountries.find(
        (country: any) => country.name === addressData.country
      );

      if (selectedCountry && selectedCountry.need_identification_number === 1 && !addressData.iossNumber) {
        setFormErrors((prevState: any) => ({
          ...prevState,
          iossNumber: 'IOSS Number is required for European country'
        }));
        return;
      }
      // if (!addressData?.state) {
      //   errors = { ...errors, state: 'State is required' };
      // }

      if (!addressData?.contactNumber) {
        errors = { ...errors, contactNumber: 'Contact No. is required' };
      }

      if (Object.keys(errors).length > 0) {
        setFormErrors(errors);
        return;
      }




      try {
        // const storedToken = JSON.parse(localStorage.getItem('tokenData') || 'null') as string | any;
        // const token = storedToken?.token?.token?.token;

        const addressApiPayload = {
          title: addressData?.title,
          type: addressData?.type,
          default: 1,
          address: {
            zip: addressData.zip,
            city: addressData.city,
            // state: addressData.state,
            state: selectedState || addressData?.state,
            country: addressData.country,
            street_address: addressData.street_address,
            firstName: addressData.firstName,
            lastName: addressData?.lastName,
            contactNumber: addressData?.contactNumber,
            company: addressData?.company
          }
        };

        const addressResponse = await axios.put(
          `https://ecomapi.foodnextdoor.shop/address/${addressData.id}`,
          addressApiPayload,
          {
            headers: {
              Accept: 'application/json',
              Authorization: `Bearer ${authToken}`,
              'Content-Type': 'application/json'
            }
          }
        );




        axios.get('https://ecomapi.foodnextdoor.shop/me', {
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        })
          .then((res) => {
            console.log(res?.data, "This is result");

            if (addressData.type === 'shipping') {
              const userData = {
                ...userSliceData,
                shippingAddress: addressResponse.data,
                address: res?.data?.address
              };
              dispatch(setUserDetails(userData));
              localStorage.setItem('UserSliceData', JSON.stringify(userData));
            }
           if (addressData?.type === "billing") {
              const userData = {
                ...userSliceData,
                billingAddress: addressResponse.data,
                address: res?.data?.address
              };
              dispatch(setUserDetails(userData));
              localStorage.setItem('UserSliceData', JSON.stringify(userData));
            }
            // if (addressData.type === 'shipping') {
            //   setAddressUser(addressResponse.data.address);
            //   localStorage.setItem('addressDeliveryData', JSON.stringify(addressResponse.data.address));
            //   const userData = {
            //     ...userSliceData,
            //     shippingAddress: addressResponse.data,
            //     address:res?.data?.address
            //   };
            //   dispatch(setUserDetails(userData));
            //   localStorage.setItem('UserSliceData', JSON.stringify(userData));
            // } else if (addressData.type === 'billing') {
            //   setBillingAddress(addressResponse.data.address);
            //   const userData = {
            //     ...userSliceData,
            //     billingAddress: addressResponse.data,
            //     address:res?.data?.address
            //   };
            //   dispatch(setUserDetails(userData));
            //   localStorage.setItem('UserSliceData', JSON.stringify(userData));
            //   localStorage.setItem('billingAddressData', JSON.stringify(addressResponse.data.address));
            // }
          })
          .catch((error) => {
            console.error('Error:', error);
          });

        setSelectedState('');

        setAddressData({
          id: '',
          title: '',
          type: '',
          zip: '',
          city: '',
          state: '',
          country: '',
          street_address: '',
          firstName: '',
          lastName: '',
          company: '',
          iossNumber: ''
        });

        setReviewShowModal(false);
      } catch (error) {
        console.error('Error updating address:', error);
      }
    }
    else {
      setFormErrors({});

      let errors = {};
      if (!addressData?.firstName) {
        errors = { ...errors, firstName: 'First Name is required' };
      }
      // if (!addressData?.lastName) {
      //   errors = { ...errors, lastName: 'Last Name is required' };
      // }
      // if (!addressData?.company) {
      //   errors = { ...errors, company: 'Company Name is required' };
      // }
      if (!addressData?.street_address) {
        errors = { ...errors, street_address: 'Address is required' };
      }
      if (!addressData?.country) {
        errors = { ...errors, country: 'Country Name is required' };
      }
      if (!addressData?.city) {
        errors = { ...errors, city: 'City Name is required' };
      }
      if (!addressData?.zip) {
        errors = { ...errors, zip: 'Zip Code is required' };
      }
      if (!addressData?.title) {
        errors = { ...errors, title: 'Alias is required' };
      }
      // if (!addressData?.iossNumber) {
      //   errors = { ...errors, iossNumber: 'IOSS Number is required' };
      // }

      const selectedCountry: any = filteredCountries.find(
        (country: any) => country.name === addressData.country
      );

      if (selectedCountry && selectedCountry.need_identification_number === 1 && !addressData.iossNumber) {
        setFormErrors((prevState: any) => ({
          ...prevState,
          iossNumber: 'IOSS Number is required for European country'
        }));
        return;
      }
      // if (!addressData?.state) {
      //   errors = { ...errors, state: 'State is required' };
      // }

      if (!addressData?.contactNumber) {
        errors = { ...errors, contactNumber: 'Contact No. is required' };
      }

      if (Object.keys(errors).length > 0) {
        setFormErrors(errors);
        return;
      }

      const addressApiPayload = {
        title: addressData?.title,
        type: "shipping",
        default: 0,
        address: {
          zip: addressData.zip,
          city: addressData.city,
          // state: addressData.state,
          state: addressData.state || selectedState,
          country: addressData.country,
          street_address: addressData.street_address,
          firstName: addressData.firstName,
          lastName: addressData?.lastName,
          contactNumber: addressData?.contactNumber,
          company: addressData?.company

        }
      };

      try {
        // const storedToken = JSON.parse(
        //   localStorage.getItem('tokenData') || 'null'
        // ) as string | any;
        // const token = storedToken?.token?.token?.token;
        console.log(authToken, "pop")

        const addressResponse = await axios.post(
          'https://ecomapi.foodnextdoor.shop/address',
          addressApiPayload,
          {
            headers: {
              Accept: 'application/json',
              Authorization: `Bearer ${authToken}`,
              'Content-Type': 'application/json'
            }
          }
        );

        if (addressData.type === 'shipping') {
          setAddressUser(addressResponse.data.address);
          localStorage.setItem(
            'addressDeliveryData',
            JSON.stringify(addressResponse.data.address)
          );
          // const userData = {
          //   ...userSliceData,
          //   shippingAddress: addressResponse.data
          // };
          // dispatch(setUserDetails(userData));
          // localStorage.setItem('UserSliceData', JSON.stringify(userData));
        } else if (addressData.type === 'billing') {
          setBillingAddress(addressResponse.data.address);
          // const userData = {
          //   ...userSliceData,
          //   billingAddress: addressResponse.data
          // };
          // dispatch(setUserDetails(userData));
          // localStorage.setItem('UserSliceData', JSON.stringify(userData));
          localStorage.setItem(
            'billingAddressData',
            JSON.stringify(addressResponse.data.address)
          );
        }
 



        axios.get('https://ecomapi.foodnextdoor.shop/me', {
          headers: {
            Authorization: `Bearer ${authToken}`
          }
        })
          .then((res) => {
            console.log(res?.data, "This result");


            if (addressData.type === 'shipping') {
              const userData = {
                ...userSliceData,
                shippingAddress: addressResponse.data,
                address: res?.data?.address
              };
              dispatch(setUserDetails(userData));
              localStorage.setItem('UserSliceData', JSON.stringify(userData));
            }
            if (addressData?.type === "billing") {
              const userData = {
                ...userSliceData,
                billingAddress: addressResponse.data,
                address: res?.data?.address
              };
              dispatch(setUserDetails(userData));
              localStorage.setItem('UserSliceData', JSON.stringify(userData));
            }

          })
          .catch((error) => {
            console.error('Error:', error);
          });

        setSelectedState('')


        setAddressData({
          title: '',
          type: '',
          zip: '',
          city: '',
          state: '',
          country: '',
          street_address: '',
          firstName: '',
          lastName: '',
          company: '',
          iossNumber: '',
          contactNumber: ''
        });

        setReviewShowModal(false);
      } catch (error) {
        console.error('Error saving address:', error);
      }
    }
  };

  //   interface CardData {
  //     product?: {
  //       minimum_quantity?: number;
  //       isMinimumQuantity?:any
  //     };
  //   }

  useEffect(() => {
    localStorage.setItem('addressDeliveryData', JSON.stringify(addressUser));
    localStorage.setItem('billingAddressData', JSON.stringify(billingAddress));
  }, [addressUser, billingAddress]);

  firebase.initializeApp({
    apiKey: 'AIzaSyCxC-X442l27N7tIfwcj08Qj_YT6yEoDZY',
    authDomain: 'myearth-stone-f64f7.firebaseapp.com',
    projectId: 'myearth-stone-f64f7',
    storageBucket: 'myearth-stone-f64f7.appspot.com',
    messagingSenderId: '167097954619',
    appId: '1:167097954619:web:f3e8db90df38a65130c71e',
    measurementId: 'G-Y68DBBBP84'
  });

  const auth = firebase.auth();
  console.log(auth);

  const savedData: any = localStorage.getItem('cardData');



  useEffect(() => {
    if (savedData) {
      const parsedData = JSON.parse(savedData);
      setCardData(parsedData);
      const initialQuantities = parsedData.map(
        (item: any) => item.product?.minimum_quantity
      );


      setQuantities(initialQuantities);
    }
  }, [savedData]);















  useEffect(() => {
    const savedData = userSliceData?.token;
    if (savedData) {
      // const parsedData = JSON.parse(savedData);
      const storedToken = userSliceData?.token;
      if (storedToken) {
        setToken(storedToken);
        // setActiveStep(2);
        setActiveStep(0)
      }
    }
    console.log(savedData, 'tokenItems');
  }, []);





  const isUserSignedIn = () => {
    const tokenData = userSliceData?.token
    return tokenData !== null;
  };

  const storedToken = JSON.parse(
    localStorage.getItem('tokenData') || 'null'
  ) as string | any;

  console.log(storedToken, 'datacart');























  const handleShowdModal = (isUpdate: any) => {

    if (!isUpdate) {
      setAddressData({
        id: '',
        title: '',
        type: 'shipping',
        firstName: '',
        lastName: '',
        company: '',
        street_address: '',
        country: '',
        city: '',
        zip: '',
        iossNumber: '',
        state: '',
        contactNumber: ''
      });
    }

    setReviewShowModal(true);
  };


  const handleClosedModal = () => {
    setReviewShowModal(false);
  };



















  useEffect(() => {
    setSelectedState(addressData.state);
  }, [addressData.state]);


  console.log(addressData?.state, "addressData?.state")





  //   const fetchStates = async (countryId:any) => {
  //     try {
  //       const response = await axios.get(
  //         `https://ecomapi.foodnextdoor.shop/states?country_id=${countryId}`
  //       );
  //       setStates(response.data);



  //       setAddressData((prevState:any) => ({
  //         ...prevState,
  //         state: selectedState
  //       }));
  //     } catch (error) {
  //       console.error('Error fetching states:', error);
  //     }
  //   };

  const fetchStates = async (countryId: any) => {
    try {
      const response = await axios.get(
        `https://ecomapi.foodnextdoor.shop/states?country_id=${countryId}`
      );
      setStates(response.data);


      if (addressData?.state && response.data.some((state: any) => state.name === addressData.state)) {
        setSelectedState(addressData.state);
      } else {
        setSelectedState('');
      }



      // setAddressData((prevState:any) => ({
      //   ...prevState,
      //   state: selectedState
      // }));

    } catch (error) {
      console.error('Error fetching states:', error);
    }
  };



  const [countries, setCountries] = useState([]);
  const [filteredCountries, setFilteredCountries] = useState([]);


  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const response = await axios.get('https://ecomapi.foodnextdoor.shop/countries');
        setCountries(response.data);
        setFilteredCountries(response.data);
        setHeaderKey(headerKey + 1)
      } catch (error) {
        console.error('Error fetching countries:', error);
      }
    };

    fetchCountries();
  }, []);


  const handleSearch = (event: any) => {
    const query = event.target.value.toLowerCase();
    const filtered = countries.filter((country: any) =>
      country.name.toLowerCase().includes(query)
    );
    setFilteredCountries(filtered);
  };

  console.log(handleSearch)

















  const isCartEmpty: any =
    cardData?.length === 0 || !cardData.some((item: any) => item.product);



  //   const updateAddressData = (type:any) => {
  //     console.log(userSliceData?.shippingAddress?.address, "userSliceDataaddress");







  //     let data:any = {};
  //     if (type === "shipping") {
  //       data = {
  //         ...userSliceData?.shippingAddress?.address,
  //         id: userSliceData?.shippingAddress?.id,
  //         type: userSliceData?.shippingAddress?.type,
  //         title: userSliceData?.shippingAddress?.title
  //       };
  //       if (data.country) {
  //         const selectedCountry:any = filteredCountries.find(
  //           (country:any) => country.name === data.country
  //         );
  //         if (selectedCountry) {
  //           if (selectedCountry.contains_states === 1) {
  //             fetchStates(selectedCountry.id);
  //           } else {
  //             setStates([]);
  //             if (!selectedCountry.contains_states) {
  //               data.state = "";
  //             }
  //           }
  //         } else {
  //           setStates([]);
  //           data.state = "";
  //         }
  //       }
  //     }

  //     if (type === "billing") {
  //       data = {
  //         ...userSliceData?.billingAddress?.address,
  //         id: userSliceData?.billingAddress?.id,
  //         type: userSliceData?.billingAddress?.type,
  //         title: userSliceData?.billingAddress?.title
  //       };
  //       if (data.country) {
  //         const selectedCountry:any = filteredCountries.find(
  //           (country:any) => country.name === data.country
  //         );
  //         if (selectedCountry) {
  //           if (selectedCountry.contains_states === 1) {
  //             fetchStates(selectedCountry.id);
  //           } else {
  //             setStates([]);
  //             if (!selectedCountry.contains_states) {
  //               data.state = "";
  //             }
  //           }
  //         } else {
  //           setStates([]);
  //           data.state = "";
  //         }
  //       }
  //     }

  //     setAddressData(data);


  //   };



  const updateAddressData = (type: any) => {
    console.log(userSliceData?.shippingAddress?.address, "userSliceDataaddress");





    let data: any = {};
    if (type === "shipping") {
      data = {
        ...userSliceData?.shippingAddress?.address,
        id: userSliceData?.shippingAddress?.id,
        type: userSliceData?.shippingAddress?.type,
        title: userSliceData?.shippingAddress?.title,
        state: userSliceData?.shippingAddress?.address?.state || '',
      };
      if (data.country) {
        const selectedCountry: any = filteredCountries.find(
          (country: any) => country.name === data.country
        );
        if (selectedCountry) {
          if (selectedCountry.contains_states === 1) {
            fetchStates(selectedCountry.id);
          } else {
            setStates([]);
            if (!selectedCountry.contains_states) {
              data.state = "";
            }
          }
        } else {
          setStates([]);
          data.state = "";
        }
      }
    }

    if (type === "billing") {
      data = {
        ...userSliceData?.billingAddress?.address,
        id: userSliceData?.billingAddress?.id,
        type: userSliceData?.billingAddress?.type,
        title: userSliceData?.billingAddress?.title,
        state: userSliceData?.billingAddress?.address?.state || '',
      };
      if (data.country) {
        const selectedCountry: any = filteredCountries.find(
          (country: any) => country.name === data.country
        );
        if (selectedCountry) {
          if (selectedCountry.contains_states === 1) {
            fetchStates(selectedCountry.id);
          } else {
            setStates([]);
            if (!selectedCountry.contains_states) {
              data.state = "";
            }
          }
        } else {
          setStates([]);
          data.state = "";
        }
      }
    } 
    setAddressData(data);
    // setSelectedState(data.state);


  };


  const ordersShow = useSelector((state: any) => state.user?.token);


  useEffect(() => {
    const delay = 1000;

    const redirectTimeout = setTimeout(() => {
      if (!ordersShow) {
        router.push('/login');
      } else {
        router.push('/myaddress');
      }
    }, delay);


    return () => clearTimeout(redirectTimeout);
  }, [ordersShow]);



  //   const handleDeleteAddress = async (addressId:any, token:any) => {
  //     const token1 = userSliceData?.token || token;

  //     try {
  //       await axios.delete(`https://ecomapi.foodnextdoor.shop/address/${addressId}`, {
  //         headers: {
  //           Authorization: `Bearer ${token1}`,
  //           'Content-Type': 'application/json',
  //         },
  //       });

  //       const updatedShippingAddress =
  //         userSliceData.shippingAddress && userSliceData.shippingAddress.id === addressId
  //           ? null
  //           : userSliceData.shippingAddress;

  //       const updatedBillingAddress =
  //         userSliceData.billingAddress && userSliceData.billingAddress.id === addressId
  //           ? null
  //           : userSliceData.billingAddress;

  //       const updatedAddresses = userSliceData.address.filter((address:any) => address.id !== addressId);


  //       const updatedUserSliceData = {
  //         ...userSliceData,
  //         shippingAddress: updatedShippingAddress,
  //         billingAddress: updatedBillingAddress,
  //         address: updatedAddresses,
  //       };

  //       console.log(updatedUserSliceData,"updatedUserSliceData")

  //       dispatch(setUserDetails(updatedUserSliceData));

  //       console.log('Address deleted successfully', updatedUserSliceData);


  //       await axios.get('https://ecomapi.foodnextdoor.shop/me', {
  //         headers: {
  //           Authorization: `Bearer ${token1}`,
  //         },
  //       })
  //         .then(res => {
  //           console.log(res?.data, "This is result");


  //           let userData = { ...updatedUserSliceData };
  //           if (addressData.type === 'shipping') {
  //             userData = {
  //               ...userData,
  //               shippingAddress: res?.data?.address
  //             };
  //           } else if (addressData.type === 'billing') {
  //             userData = {
  //               ...userData,
  //               billingAddress: res?.data?.address
  //             };
  //           }

  //           dispatch(setUserDetails(userData));
  //           localStorage.setItem('UserSliceData', JSON.stringify(userData));
  //         })
  //         .catch(error => {
  //           console.error('Failed to fetch updated user data', error);
  //         });
  //     } catch (error) {
  //       console.error('Failed to delete address', error);
  //     }
  //   };



  const handleDeleteAddress = async (addressId: any, token: any) => {
    const token1 = userSliceData?.token || token;

    try {
      await axios.delete(`https://ecomapi.foodnextdoor.shop/address/${addressId}`, {
        headers: {
          Authorization: `Bearer ${token1}`,
          'Content-Type': 'application/json',
        },
      });

      let updatedUserSliceData = { ...userSliceData };


      if (
        updatedUserSliceData.shippingAddress &&
        updatedUserSliceData.shippingAddress.id === addressId
      ) {
        updatedUserSliceData.shippingAddress = null;
      }

/* 
      if (
        updatedUserSliceData.billingAddress &&
        updatedUserSliceData.billingAddress.id === addressId
      ) {
        updatedUserSliceData.billingAddress = null;
      }
 */
      updatedUserSliceData.address = updatedUserSliceData.address.filter(
        (address: any) => address.id !== addressId
      );

      console.log(updatedUserSliceData, "updatedUserSliceData");

      dispatch(setUserDetails(updatedUserSliceData));

      console.log('Address deleted successfully', updatedUserSliceData);


      await axios
        .get('https://ecomapi.foodnextdoor.shop/me', {
          headers: {
            Authorization: `Bearer ${token1}`,
          },
        })
        .then((res) => {
          console.log(res?.data, "This is result");

          const userData = { ...updatedUserSliceData };


          if (
            userSliceData.shippingAddress &&
            userSliceData.shippingAddress.id === addressId
          ) {
            userData.shippingAddress = res?.data?.address.find(
              (address: any) => address.type === 'shipping'
            );
          }

         /*  if (
            userSliceData.billingAddress &&
            userSliceData.billingAddress.id === addressId
          ) {
            userData.billingAddress = res?.data?.address.find(
              (address: any) => address.type === 'billing'
            );
          } */

          updatedUserSliceData = userData;

          dispatch(setUserDetails(userData));
          localStorage.setItem('UserSliceData', JSON.stringify(userData));
        })
        .catch((error) => {
          console.error('Failed to fetch updated user data', error);
        });


      console.log(updatedUserSliceData.address);

    } catch (error) {
      console.error('Failed to delete address', error);
    }
  };
















  const filterAddress = (event: any, type: any) => {
    console.log(event?.target?.value, "event")
  
    const id = event?.target?.value
    if (type === "shipping") {
      const filterShippingAddresByTitle = userSliceData?.address?.filter((item: any) => {
        console.log(item, "this is item")
        return item?.id == id && item?.type === "shipping"
      })
      dispatch(setUserDetails({
        ...userSliceData,
        shippingAddress: filterShippingAddresByTitle[0]
      }))


    }
   /*  if (type === "billing") {
      const filterBillingAddresByTitle = userSliceData?.address?.filter((item: any) => {
        console.log(item, "this is item")
        return item?.id == id && item?.type === "billing"
      })
      console.log(filterBillingAddresByTitle, "filterBillingAddresByTitle")
      dispatch(setUserDetails({
        ...userSliceData,
        billingAddress: filterBillingAddresByTitle[0]
      }))
    } */
  }

  console.log(charges, setCharges, quantities, activeStep, email, password, setEmail, setPassword, useDeliveryAddress, setUseDeliveryAddress, setAddresserName, paymentMethod);
  console.log(setPaymentMethod, setOrderData, emailError, setEmailError, passwordError, setPasswordError, cardData, isUserSignedIn, isCartEmpty)


  const handleLogout = () => {
    localStorage.clear();

    router.push('/');
  };


  return (
    <>
      <Header key={headerKey} />


      <Container>
        <Row className="justify-content-center mb-5">

          {showReviewModal && (
            <>
              <div></div>
              <Modal
                show={showReviewModal}
                onHide={handleClosedModal}
                size="lg"
                className="review-modal"
              >
                <Modal.Header closeButton>
                  <Modal.Title id="review-modal-title">
                    Your Address Details
                  </Modal.Title>
                </Modal.Header>
                <Modal.Body className='p-4 px-md-5 mt-2 modal-body'>
                  <Form onSubmit={(event) => handleAddressSubmit(event, token)} className='addaddress-popup row'>
                    <div className='col-12'>


{/* 
                      <select
                        name="type"
                        value={addressData?.type}
                        onChange={handleAddressChange}
                        className="cart-address-label form-control icon"

                      >
                        <option value="billing">Billing</option>
                        <option value="shipping">Shipping</option>
                      </select> */}
                    </div>





                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>First Name*</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your first name"
                        value={addressData?.firstName}
                        onChange={handleAddressChange}
                        name="firstName"
                        isInvalid={formErrors?.firstName}
                      />
                      {formErrors.firstName && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.firstName}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>
                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>Last Name</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your last name"
                        value={addressData?.lastName}
                        onChange={handleAddressChange}
                        name="lastName"
                        isInvalid={formErrors?.lastName}
                      />
                      {formErrors.lastName && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.lastName}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>

                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>Company</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your company name"
                        value={addressData?.company}
                        onChange={handleAddressChange}
                        name="company"
                        // isInvalid={formErrors?.company}
                      />
                      {/* {formErrors.company && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.company}
                        </Form.Control.Feedback>
                      )} */}
                    </Form.Group>

                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>Address*</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your address"
                        value={addressData?.street_address}
                        onChange={handleAddressChange}
                        name="street_address"
                        isInvalid={formErrors?.street_address}
                      />
                      {formErrors.street_address && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.street_address}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>



                    <Form.Group controlId="" className="form-group col-md-4">
                      <Form.Label>Country*</Form.Label>
                      <Form.Control
                        as="select"
                        value={addressData?.country}
                        onChange={handleAddressChange}
                        name="country"
                      // onKeyUp={handleSearch}
                      >
                        <option value="">Choose your country</option>
                        {filteredCountries
                          .slice()
                          .sort((a: any, b: any) => a.name.localeCompare(b.name))
                          .map((country: any) => (
                            <option key={country.id} value={country.name}>
                              {country.name}
                            </option>
                          ))}
                      </Form.Control>
                      {formErrors.country && (
                        <div className="error" style={{ color: 'red' }}>
                          {formErrors.country}
                        </div>
                      )}
                    </Form.Group>




                    {filteredCountries.some(
                      (country: any) =>
                        country.name === addressData.country && country.contains_states === 1
                    ) ? (
                      <Form.Group controlId="" className="form-group col-md-4">
                        <Form.Label>State</Form.Label>
                        <Form.Control
                          as="select"
                          value={selectedState}
                          onChange={(event) => {
                            setSelectedState(event.target.value);
                            setAddressData((prevState: any) => ({
                              ...prevState,
                              state: event.target.value,
                            }));
                          }}
                          name="state"
                        >
                          <option value="">Choose your state</option>
                          {/* {states.map((state: any) => (
        <option
          key={state.id}
          value={state.name}
          selected={state.name === addressData.state}
        >
          {state.name}
        </option>
      ))} */}


                          {states
                            .slice()
                            .sort((a: any, b: any) => a.name.localeCompare(b.name))
                            .map((state: any) => (
                              <option
                                key={state.id}
                                value={state.name}
                                selected={state.name === addressData.state}
                              >
                                {state.name}
                              </option>
                            ))}
                        </Form.Control>
                      </Form.Group>
                    ) : null}



                    <Form.Group controlId="" className="form-group col-md-4">
                      <Form.Label>City</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your city"
                        value={addressData?.city}
                        onChange={handleAddressChange}
                        name="city"
                        isInvalid={formErrors?.city}
                      />
                      {formErrors.city && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.city}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>

                    <Form.Group controlId="" className="form-group col-md-4">
                      <Form.Label>Zip / Postal Code*</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your zip code"
                        value={addressData?.zip}
                        onChange={handleAddressChange}
                        name="zip"
                        isInvalid={formErrors?.zip}
                      />
                      {formErrors.zip && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.zip}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>

                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>IOSS Number <span className='text-14'>(*Required for European country)</span></Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your IOSS number"
                        value={addressData?.iossNumber}
                        onChange={handleAddressChange}
                        name="iossNumber"
                        isInvalid={formErrors?.iossNumber}
                      />
                      {formErrors.iossNumber && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.iossNumber}
                        </Form.Control.Feedback>
                      )}
                    </Form.Group>



                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>Additional information</Form.Label>
                      <Form.Control type="text" placeholder="" />
                    </Form.Group>

                    <Form.Group controlId="" className="form-group col-md-6">
                      <Form.Label>Contact Number*</Form.Label>
                      <Form.Control
                        type="number"
                        placeholder="Enter your contact number"
                        value={addressData?.contactNumber}
                        onChange={handleAddressChange}
                        name="contactNumber"
                        isInvalid={formErrors?.contactNumber}
                      />
                      {formErrors.contactNumber && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors.contactNumber}
                        </Form.Control.Feedback>
                      )}



                      {addressData?.contactNumber && addressData.contactNumber.length > 10 && !formErrors.contactNumber && (
                        <div className="error" style={{ color: 'red', fontSize: '.875em' }}>
                          Phone number cannot be greater than 10 digits.
                        </div>
                      )}
                    </Form.Group>
                    <Form.Group controlId="" className="form-group col-md-12">
                      <Form.Label>Assign an address alias for future reference *</Form.Label>
                      <Form.Control
                        type="text"
                        placeholder="Enter your alias"
                        value={addressData?.title}
                        onChange={handleAddressChange}
                        name="title"
                        isInvalid={formErrors?.title}
                      />
                      {formErrors.title && (
                        <Form.Control.Feedback type="invalid">
                          {formErrors?.title}
                        </Form.Control.Feedback>
                      )}

                    </Form.Group>

                    <Form.Group className="mb-3" style={{ marginTop: '20px' }}>
                      <Button type="submit" variant="theme">
                        Submit
                      </Button>
                      <Link href='/myaddress' onClick={()=>setReviewShowModal(false)}>
                      <Button
                        type="button"
                        variant="theme-outline"
                        className="ms-4"
                      >
                        Back
                      </Button>
                      </Link>
                    </Form.Group>
                  </Form>
                </Modal.Body>
              </Modal>
            </>
          )}
          <Col lg={11}>{
            ordersShow ? (
              <div className="myaccount-wrap mt-4 pt-2">
                <Row className="gx-0">
                  <Col className="myacc-sidebar">
                    <h2 className="myacc-heading">My Account</h2>
                    <Nav
                      defaultActiveKey="/myaddress"
                      className="flex-column"
                    >
                      <Nav.Link href="/myorders">
                        <i className="fa-light fa-receipt"></i>My Orders
                      </Nav.Link>
                      <Nav.Link href="/myaddress">
                        <i className="fa-light fa-address-book"></i>My Addresses
                      </Nav.Link>
                      <Nav.Link href="/personalInfo">
                        <i className="fa-light fa-circle-info"></i>My Personal
                        Information
                      </Nav.Link>
                      <Nav.Link href="/myvoucher">
                        <i className="fa-light fa-gift"></i>My Vouchers
                      </Nav.Link>
                      <Nav.Link href="/wishlist">
                        <i className="fa-light fa-heart"></i>My Wishlist
                      </Nav.Link>
                      {/* <Nav.Link href="/requestquote">
                        <i className="fa-sharp fa-light fa-message-quote"></i>
                        Request A Quote
                      </Nav.Link> */}
                      <Nav.Link href="/changepassword">
                        <i className="fa-light fa-key"></i>Change Password
                      </Nav.Link>
                      <Nav.Link href="/customerEnquiry">
                      <i className="fa-light fa-key"></i>Customer Enquiry
                    </Nav.Link>
                      <Nav.Link href="/" onClick={handleLogout}>
                        <i className="fa-light fa-power-off"></i>Logout
                      </Nav.Link>
                    </Nav>
                  </Col>

                  <Col className="myacc-rightside ps-5">
                    <h2 className="myacc-page-title">My Addresses</h2>
                    <div className="myaccount-content">
                      <p>
                        Please configure your default billing and delivery
                        addresses when placing an order. You may also add
                        additional addresses, which can be useful for sending
                        gifts or receiving an order at your office. Be sure to
                        update your personal information if it has changed.
                      </p>



                      {Object.keys(userSliceData || {}).length > 0 && (
                        <>

                      {/*     <div className="col-md-6">
                            <select
                              name=""
                              id=""
                              className="cart-address-label form-control icon"
                              onChange={(event: any) => filterAddress(event, "shipping")}
                              value={userSliceData?.shippingAddress?.id}
                            >
                          
                              {shippingAddressOption?.map((item: any) => {
                                return (
                                  <option key={item?.id} value={item?.id}>
                                    {item?.title}
                                  </option>
                                );
                              })}
                            </select>
                          </div> */}
                          {userSliceData?.address?.map((item: any) => {
                              console.log(item, "this us item")
                              return <div className="cart-address-item bg-light mt-4">
                          <Row className="gx-0">
                              <Col lg={8} className="">
                                <div className="col-md-6">
                                  <div className="">
                                    <h4>{item.title}</h4>
                                    <p>
                                      {item.address?.firstName} {item.address?.lastName}
                                    </p>
                                    <p>{item.address?.street_address}</p>
                                    <p>{item.address?.zip}</p>
                                   
                                        <p> {item.address.company}</p>
                                        <p> {item.address.contactNumber}</p>
                                         <p>
                                      {item.address?.state &&
                                        `${item.address?.state}, `}
                                      {item.address?.country}
                                        </p>
                                  </div>
                                </div>
                              </Col>
                              <Col lg={4} className="address-buttons text-end">
                                <a href="#" className="btn-theme-outline btn-sm position-static me-3" onClick={() => {
                                  updateAddressData("shipping");
                                  handleShowdModal('true');
                                }}>
                                  Update
                                </a>
                                <a
                                  href="#"
                                  className="btn-theme-outline outline-grey btn-sm position-static"
                                  onClick={() => handleDeleteAddress(userSliceData?.shippingAddress?.id, token)}
                                >
                                  Delete
                                </a>
                              </Col>
                            </Row>
                           
                             
                           
                              </div>
                               })}
                        </>
                      )}

                      {userSliceData?.billingAddress &&
                        <>
                          <div className="col-md-6">
                        {/*     {billingAddressOption?.length > 0 ? (
                              <select
                                name=""
                                id=""
                                className="cart-address-label form-control icon"
                                onChange={(event: any) => filterAddress(event, "billing")}
                                // value={userSliceData?.billingAddress?.id}
                                value={userSliceData?.billingAddress?.id}
                              >
                                {billingAddressOption?.map((item: any) => (
                                  <option key={item?.id} value={item?.id}>
                                    {item?.title}
                                  </option>
                                ))}
                              </select>
                            ) : null} */}
                        </div>
                        {Array.isArray(userSliceData?.billingAddress) &&userSliceData?.billingAddress?.map((item: any) => {
                          console.log(item, "this us itemmmmm")
                          return  <div className="cart-address-item bg-light mt-4">
                            <Row className="gx-0">
                              <Col lg={8} className="">
                                {userSliceData?.billingAddress && (
                                  <div className="">
                                    <h4>Billing Address</h4>
                                    <p>
                                      {userSliceData?.billingAddress?.address?.firstName} {userSliceData?.billingAddress?.address?.lastName}
                                    </p>
                                    <p>
                                      {
                                        userSliceData?.billingAddress?.address
                                          ?.street_address
                                      }
                                    </p>
                                    <p>{userSliceData?.billingAddress?.address?.zip}</p>
                                    {/* <p>
                              {userSliceData?.billingAddress?.address?.state},{' '}
                              {userSliceData?.billingAddress?.address?.country}
                            </p> */}
                                    <p>
                                      {userSliceData?.billingAddress?.address?.state &&
                                        `${userSliceData?.billingAddress?.address?.state}, `}
                                      {userSliceData?.billingAddress?.address?.country}
                                    </p>


                                  </div>
                                )}
                              </Col>
                              <Col lg={4} className="address-buttons text-end">
                                <a href="#" className="btn-theme-outline btn-sm position-static me-3" onClick={() => {
                                  updateAddressData("shipping")
                                  handleShowdModal('true')
                                }}>
                                  Update
                                </a>
                                <a
                                  href="#"
                                  className="btn-theme-outline outline-grey btn-sm position-static"
                                  onClick={() => handleDeleteAddress(userSliceData?.billingAddress?.id, token)}
                                >
                                  Delete
                                </a>
                              </Col>












                            </Row>
                          </div>
                        })
}
                        </>
                      }









                      <Form.Group className="form-group buttons mt-5">
                        <Button
                          onClick={() => {
                            handleShowdModal(false);
                          }}
                          type="submit"
                          variant="theme-outline"
                          className="me-4"
                        >
                          <i className="fa-sharp fa-solid fa-plus me-2 text-16"></i>
                          Add New Address
                        </Button>
                        <Link href='/home'>
                        <Button type="button" variant="theme-outline">
                          Home
                        </Button>
                        </Link>
                      </Form.Group>



                    </div>
                  </Col>
                </Row>
              </div>
            ) : (
              <p>No Address found</p>
            )
          }

          </Col>
        </Row>
      </Container>




















      <Footer />
    </>
  );
}

export default ShoppingCart;
Leave a Comment