"use client";
import React, {
  useState,
  useEffect,
  JSX,
  Dispatch,
  SetStateAction,
} from "react";
import axios from "@/utils/axios-config";
import {
  Steps,
  Radio,
  Button,
  Select,
  Input,
  Checkbox,
  Collapse,
  message,
  Tooltip,
} from "antd";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSelector, useDispatch } from "react-redux";
import Image from "next/image";
import type { RadioChangeEvent } from "antd";
import { useTranslations, useLocale } from "next-intl";
import { addEditAddress } from "@/store/address/actions";
import { FaArrowRightLong } from "react-icons/fa6";
import { FaPlus } from "react-icons/fa";

import {
  IoBagCheckOutline,
  IoLocationSharp,
  IoCall,
  IoClose,
} from "react-icons/io5";
import {
  fetchAddressIdSuccess,
  fetchAddressSuccess,
  setEditingAddress,
  fetchSelectedBranch,
} from "@/store/address/actions";
import type { CheckboxProps } from "antd";
import { IoIosCloseCircleOutline } from "react-icons/io";
import { ArrowRightOutlined } from "@ant-design/icons";
import SkeletonAddressList from "../skeletons/skeleton-addresses";
import { fetchBranchIdSuccess } from "@/store/address/actions";
import {
  FETCH_CART_SUCCESS,
  FETCH_CART_LENGTH,
  fetchPrescriptionSuccess,
  fetchMinOrderPrice,
} from "@/store/cart/actions";
import { DivIcon } from "leaflet";
export interface OfferDetails {
  offer_price: string | number;
  offer_free_quantity: number;
  offer_buy_quantity: number;
  offer_discount_type: number;
  offer_discount_value: number;
}

export interface availableProduct {
  available_quantity: number;
  required_quantity: number;
  brand_name: string;
  is_available: number;
  offer_details: OfferDetails | null;
  product_id: number;
  product_image: string;
  product_name: string;
  product_price: string;
}

export interface props {
  itemsTotalPrice: number;
  vatRatio: number;
  vat: number;
  promoCodeValue?: string;
  branchesDisplayAction: string;
  setBranchesDisplayAction: Dispatch<SetStateAction<any>>;
  deliveryType: string;
  setDeliveryType: Dispatch<SetStateAction<any>>;
  length: number;
  discount: number;
  totalShipping: number;
  discountType: number;
  itemsTotalPriceExcVat: number;
  addressContinueBtnClicked: boolean;
  setHasPrescription: Dispatch<SetStateAction<any>>;
  setTotalIncludeVat: Dispatch<SetStateAction<any>>;
  setTotalExcludeVat: Dispatch<SetStateAction<any>>;
  setPaymentPartTotalIncludeVat: Dispatch<SetStateAction<any>>;
  setPaymentPartTotalExcludeVat: Dispatch<SetStateAction<any>>;
  setCartItems: Dispatch<SetStateAction<any[]>>;
  cartItems: any[];
  setPharmaciesArrLength: Dispatch<SetStateAction<number>>;
}

export default function CartAddress({
  itemsTotalPrice,
  vatRatio,
  vat,
  discount,
  promoCodeValue,
  totalShipping,
  discountType,
  itemsTotalPriceExcVat,
  length,
  addressContinueBtnClicked,
  setPaymentPartTotalIncludeVat,
  setPaymentPartTotalExcludeVat,
  setDeliveryType,
  branchesDisplayAction,
  setBranchesDisplayAction,
  //setTotalExcludeVat,
  setHasPrescription,
  cartItems,
  setCartItems,
  //setTotalIncludeVat,
  setPharmaciesArrLength,
}: props) {
  const [value, setValue] = useState(1);
  const [showAddressPart, setShowAddressPart] = useState("main");
  const [totalIncludeVat, setTotalIncludeVat] = useState(itemsTotalPrice);
  const [totalExcludeVat, setTotalExcludeVat] = useState(itemsTotalPriceExcVat);
  const [checkedAddress, setCheckedAddress] = useState(0);

  // const [selectedBranch, setSelectedBranch] = useState<any>();
  const [closesPharmacies, setClosestPharmacies] = useState<any>([]);
  const [addressesLoading, setAddressesLoading] = useState(false);
  const { TextArea } = Input;
  const router = useRouter();
  const dispatch = useDispatch();
  const locale = useLocale();
  const { pickupMethod } = useSelector((state: { Cart: any }) => state.Cart);
  const {
    addressId,
    addresses,
    branchId,
    addressBranchChanged,
    selectedBranch,
  } = useSelector((state: { Address: any }) => state.Address);
  const [loading, setLoading] = useState(false);
  const [profileData, setProfileData] = useState<any>({});
  const [address, setAddress] = useState<any>({});
  const t = useTranslations();
  const availabilityObj: { [key: string]: JSX.Element } = {
    "1": (
      <p className="text-primary text-[14px] md:text-[16px]">
        {t("available")}
      </p>
    ),
    "2": (
      <p className="text-[#EFC04D] text-[14px] md:text-[16px]">
        {t("partially-available")}
      </p>
    ),
    "3": (
      <p className="text-[#ff4d4f] text-[14px] md:text-[16px]">
        {t("not-available")}
      </p>
    ),
  };

  useEffect(() => {
    if (selectedBranch) {
      const totalPrice = +eval(
        selectedBranch?.product_availability
          ?.map((item: any) => {
            if (
              Number(item?.offer_details?.offer_price) <=
                Number(item?.product_price) &&
              item?.offer_details?.offer_free_quantity === 0
            ) {
              return (
                Number(item?.offer_details?.offer_price) *
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity))
              );
            } else if (
              Number(item?.offer_details?.offer_price) <=
                Number(item?.product_price) &&
              item?.offer_details?.offer_free_quantity > 0
            ) {
              const offerQuantity =
                Math.floor(
                  (Number(item?.required_quantity) <=
                  Number(item?.available_quantity)
                    ? Number(item?.required_quantity)
                    : Number(item?.available_quantity)) /
                    (Number(item?.offer_details?.offer_free_quantity) +
                      Number(item?.offer_details?.offer_buy_quantity)),
                ) * Number(item?.offer_details?.offer_free_quantity);

              const total =
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity)) >= offerQuantity &&
                offerQuantity > 0
                  ? item?.offer_details?.offer_discount_type === 1
                    ? offerQuantity *
                        (Number(item?.offer_details?.offer_price) -
                          Number(item?.offer_details?.offer_discount_value)) +
                      ((Number(item?.required_quantity) <=
                      Number(item?.available_quantity)
                        ? Number(item?.required_quantity)
                        : Number(item?.available_quantity)) -
                        offerQuantity) *
                        Number(item?.offer_details?.offer_price)
                    : offerQuantity * Number(item?.offer_details?.offer_price) -
                      (offerQuantity *
                        Number(item?.offer_details?.offer_price) *
                        Number(item?.offer_details?.offer_discount_value)) /
                        100 +
                      ((Number(item?.required_quantity) <=
                      Number(item?.available_quantity)
                        ? Number(item?.required_quantity)
                        : Number(item?.available_quantity)) -
                        offerQuantity) *
                        Number(item?.offer_details?.offer_price)
                  : (Number(item?.required_quantity) <=
                    Number(item?.available_quantity)
                      ? Number(item?.required_quantity)
                      : Number(item?.available_quantity)) *
                    Number(item?.offer_details?.offer_price);

              return total;
            } else {
              return (
                Number(item?.product_price) *
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity))
              );
            }
          })
          .join("+"),
      )?.toFixed(2);

      const totalPriceExcVat = +eval(
        selectedBranch?.product_availability
          ?.map((item: any) => {
            if (
              Number(item?.offer_details?.offer_price) <=
                Number(item?.product_price) &&
              Number(item?.offer_details?.offer_free_quantity) === 0
            ) {
              const total =
                Number(item?.offer_details?.offer_price) /
                (100 + Number(item?.tax));
              return (
                total *
                100 *
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity))
              );
            } else if (
              Number(item?.offer_details?.offer_price) <=
                Number(item?.product_price) &&
              item?.offer_details?.offer_free_quantity > 0
            ) {
              const offerQuantity =
                Math.floor(
                  (Number(item?.required_quantity) <=
                  Number(item?.available_quantity)
                    ? Number(item?.required_quantity)
                    : Number(item?.available_quantity)) /
                    (Number(item?.offers_details?.offer_free_quantity) +
                      Number(item?.offers_details?.offer_buy_quantity)),
                ) * Number(item?.offer_details?.offer_free_quantity);
              const itemExcVat =
                (Number(item?.offer_details?.offer_price) /
                  (100 + Number(item?.tax))) *
                100;
              const total =
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity)) >= offerQuantity &&
                offerQuantity > 0
                  ? item?.offer_details?.offer_discount_type === 1
                    ? offerQuantity *
                        (Number(itemExcVat) -
                          Number(item?.offer_details?.offer_discount_value)) +
                      ((Number(item?.required_quantity) <=
                      Number(item?.available_quantity)
                        ? Number(item?.required_quantity)
                        : Number(item?.available_quantity)) -
                        offerQuantity) *
                        Number(itemExcVat)
                    : offerQuantity * Number(itemExcVat) -
                      (offerQuantity *
                        Number(itemExcVat) *
                        Number(item?.offer_details?.offer_discount_value)) /
                        100 +
                      ((Number(item?.required_quantity) <=
                      Number(item?.available_quantity)
                        ? Number(item?.required_quantity)
                        : Number(item?.available_quantity)) -
                        offerQuantity) *
                        Number(itemExcVat)
                  : (Number(item?.required_quantity) <=
                    Number(item?.available_quantity)
                      ? Number(item?.required_quantity)
                      : Number(item?.available_quantity)) * Number(itemExcVat);

              return total;
            } else {
              return (
                Number(item?.price_before) *
                (Number(item?.required_quantity) <=
                Number(item?.available_quantity)
                  ? Number(item?.required_quantity)
                  : Number(item?.available_quantity))
              );
            }
          })
          .join("+"),
      )?.toFixed(2);
      //console.log("totalPrice", totalPrice);
      setTotalIncludeVat(totalPrice);
      setTotalExcludeVat(totalPriceExcVat);
      setPaymentPartTotalIncludeVat(totalPrice);
      setPaymentPartTotalExcludeVat(totalPriceExcVat);
    }
  }, [selectedBranch]);

  useEffect(() => {
    const fetchClosestPharmacies = async () => {
      dispatch(fetchBranchIdSuccess(undefined));
      const obj: Record<string, any> = { address_id: addressId };
      if (pickupMethod === 1) {
        obj["delivery_method"] = 1;
      }
      try {
        const response = await axios.post(`/branch-products`, obj);

        const { data } = await response?.data;
        console.log("closest pharmacies", data);
        setBranchesDisplayAction(data?.action);
        if (pickupMethod === 2 && data?.action === "auto_select") {
          // console.log("branchId", data[0]);
          dispatch(fetchBranchIdSuccess(data?.branches[0]?.branch_id));
          dispatch(fetchSelectedBranch(data?.branches[0]));
          setPaymentPartTotalIncludeVat(totalIncludeVat);
          setPaymentPartTotalExcludeVat(totalExcludeVat);
          setClosestPharmacies([data?.branches[0]]);
          setDeliveryType(data?.branches[0]?.delivery_type);
        } else {
          setClosestPharmacies([...data?.branches]);
        }
        // console.log("dattta", data);
        setPharmaciesArrLength(data?.branches?.length);

        //console.log("addresses", data);
      } catch (err: any) {
        if (err?.status === 422) {
          setClosestPharmacies([]);
        }
        // console.log('pharmacyErr', err)
        message.error(err?.message);
        //setClosestPharmacies([]);
      }
    };
    if (addressId) {
      fetchClosestPharmacies();
    }
  }, [addressId]);

  useEffect(() => {
    const theAddress = addresses?.filter(
      (item: any) => item?.id === addressId,
    )[0];
    setAddress(theAddress);
  }, [addressId]);
  const onChange = (value: string) => {
    console.log(`selected ${value}`);
  };

  const onSearch = (value: string) => {
    console.log("search:", value);
  };
  const onCheckBoxChange: CheckboxProps["onChange"] = (e) => {
    console.log(`checked = ${e.target.checked}`);
  };

  ////addresses data
  useEffect(() => {
    const fetchAddressesData = async () => {
      setLoading(true);
      window.scrollTo(0, 0);
      try {
        const response = await axios.get(`addresses`);

        const { data } = await response?.data;

        dispatch(fetchAddressSuccess(data));
        // if (!addressId) {
        //   dispatch(fetchAddressIdSuccess(data[0]?.id));
        // }
        setLoading(false);
        // console.log("addresses", data);
      } catch (err: any) {
        setLoading(false);
      }
    };
    fetchAddressesData();
  }, []);

  const handleRadioChange = (id: number) => {
    // setSelectedAddress(id);
    dispatch(fetchAddressIdSuccess(id));
    //dispatch(fetchBranchIdSuccess(undefined));
  };

  const getTotalPriceAndExcVatPrice = (obj: any) => {};

  return (
    <>
      {addresses?.length > 0 ? (
        <div>
          <div className=" mx-auto  py-[30px] ">
            {showAddressPart === "main" && (
              <>
                <div className="flex flex-col items-center md:flex-row md:items-start justify-between">
                  <div className="w-full md:w-[calc(55%-15px)]">
                    {addresses?.length === 0 ? (
                      <div className="   pb-[2rem] flex flex-col items-center justify-center">
                        <p className="py-4">{t("no-addresses")}</p>
                        <Link
                          href={`/${locale}/address/new-address`}
                          locale={false}
                          onClick={() => {
                            dispatch(addEditAddress("add"));
                          }}
                          className="bg-[#03B89E] flex justify-center items-center border border-[#03B89E] text-[19px] font-[700] rounded-md text-[#FFFFFF] w-[399px] h-[56px] hover:bg-[#fff] hover:text-[#03B89E] transition-colors duration-500 max-[400px]:min-w-[100%]"
                        >
                          {t("add-btn")}
                          <ArrowRightOutlined
                            className={`mx-[5px] ${
                              locale === "ar" ? "rotate-180" : ""
                            }`}
                          />
                        </Link>
                      </div>
                    ) : (
                      <section className=" rounded-[10px] mb-4 border-solid border-[1px] border-primary   pb-4">
                        <div
                          className={`container mx-auto px-3 relative `}
                          id="scroll-section"
                        >
                          {/* <h2 className="text-[#424242] font-[600] text-[24px] mb-[5px]">
          {t("address-title")}
        </h2> */}
                          <div className="flex justify-between items-center border-b-[1px] border-gray-300 mb-[10px] py-2">
                            <p className=" font-semibold   text-[18px] sm:text-[20px]  sticky top-0 py-2 z-10 bg-white">
                              {t("address-desc")}
                            </p>
                            <Tooltip
                              title={t("add-new-address")}
                              color="#03B89E"
                            >
                              <Link
                                href={`/${locale}/address/new-address`}
                                onClick={() => {
                                  dispatch(addEditAddress("add"));
                                }}
                                className="bg-[#03B89E] flex justify-center items-center border border-[#03B89E] text-[19px] font-[700] rounded-md text-[#FFFFFF] p-2 hover:bg-[#fff] hover:text-[#03B89E] transition-colors duration-500 w-fit"
                              >
                                <FaPlus />
                              </Link>
                            </Tooltip>
                          </div>
                          <div className="max-h-[300px] md:max-h-[400px] overflow-y-auto px-2">
                            {addresses?.map((address: any) => (
                              <div
                                key={address.id}
                                className={`py-[20px] mb-[20px] border ${
                                  address.id === addressId
                                    ? "border-[#03B89E]"
                                    : "border-[#E5E5E5]"
                                } rounded-lg`}
                              >
                                <div className="flex items-center px-[20px]">
                                  <Radio
                                    type="primary"
                                    // value={address.id}
                                    checked={addressId === address.id}
                                    onChange={() =>
                                      handleRadioChange(address.id)
                                    }
                                    className={`mr-3  mb-[10px] ${
                                      addressId === address.id
                                        ? "text-[#03B89E]"
                                        : "text-[#E5E5E5]"
                                    }`}
                                  />
                                  <h3 className="text-[20px] font-[500] text-[#424242] mb-[10px]">
                                    {address.address}
                                  </h3>
                                </div>
                                <hr
                                  className={`bg-[#03B89E] h-[2px] w-[100%] mb-[12px] ${
                                    addressId === address.id
                                      ? "bg-[#03B89E]"
                                      : "bg-[#E5E5E5]"
                                  }`}
                                />
                                <p className="text-[16] font-[400] text-[#424242] px-[20px] mb-[10px]">
                                  <strong>{t("governate")}:</strong>{" "}
                                  {address.governorate}
                                </p>
                                <p className="text-[16] font-[400] text-[#424242] px-[20px] mb-[10px]">
                                  <strong>{t("city")}:</strong> {address.city}
                                </p>
                                <p className="text-[16] font-[400] text-[#424242] px-[20px] mb-[10px]">
                                  <strong>{t("details")}:</strong>{" "}
                                  {address.address}
                                </p>
                              </div>
                            ))}
                          </div>

                          {/* <ProductList title={t("similar-products")}/> */}
                        </div>
                      </section>
                    )}
                  </div>
                  <div className="md:ms-4 w-full md:w-[calc(45%-15px)]">
                    <div className="bg-[#F6F6F6] rounded-[10px] p-4">
                      <div className="flex justify-center items-center py-1">
                        <p className="font-semibold">
                          <span className="me-1 text-primary">{length}</span>
                          {length > 1 ? t("items") : t("item")}
                        </p>
                        <p className="flex flex-1 h-[1px] ms-2 bg-gray-300">
                          {" "}
                        </p>
                      </div>
                      <div className="flex justify-between items-center py-1">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("subtotal-exc-vat")}
                        </p>
                        <div className="flex items-center min-w-[50px]">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {Number(totalExcludeVat).toFixed(2)}
                          </p>
                          {/* <span className="inline-block "> */}
                          <Image
                            src={"/images/ryial.svg"}
                            alt="currancy icon"
                            width={12}
                            height={12}
                            className="ms-1"
                          />
                          {/* </span> */}
                        </div>
                      </div>
                      <div className="flex justify-between items-center py-1 ">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("subtotal-incl-vat")}
                        </p>
                        <div className="flex items-center min-w-[55px]">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {Number(totalIncludeVat).toFixed(2)}
                          </p>
                          {/* <span className="inline-block "> */}
                          <Image
                            src={"/images/ryial.svg"}
                            alt="currancy icon"
                            width={12}
                            height={12}
                            className="ms-1"
                          />
                          {/* </span> */}
                          {/* {t("sar")} */}{" "}
                        </div>
                      </div>
                      {/* <div className="flex justify-between items-center py-1">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("vat")}
                        </p>
                        <div className="flex items-center">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {
                              
                              (
                                ((Number(totalIncludeVat) -
                                  Number(totalExcludeVat)) /
                                  Number(totalExcludeVat)) *
                                100
                              ).toFixed(2)
                            }
                            
                          </p>
                          <span className=" w-[27px] flex justify-center items-center">
                            %
                          </span>
                        </div>
                      </div> */}
                      <div className="flex justify-between items-center py-1">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("vat-value")}
                        </p>
                        <div className="flex items-center">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {(
                              Number(totalIncludeVat) - Number(totalExcludeVat)
                            ).toFixed(2)}
                            {/* {t("sar")} */}{" "}
                          </p>
                          <span className="inline-block ">
                            <Image
                              src={"/images/ryial.svg"}
                              alt="currancy icon"
                              width={12}
                              height={12}
                              className="ms-1"
                            />
                          </span>
                        </div>
                      </div>

                      {pickupMethod === 2 && (
                        <>
                          <div className="flex justify-between items-center py-1">
                            <p className="font-semibold max-w-[225px] sm:max-w-full">
                              {t("total-shipping")}
                            </p>
                            <div className="flex items-center">
                              <p className="text-gray-600 text-[17px] font-semibold">
                                {Number(totalShipping).toFixed(2)}
                              </p>
                              <span className="inline-block ">
                                <Image
                                  src={"/images/ryial.svg"}
                                  alt="currancy icon"
                                  width={12}
                                  height={12}
                                  className="ms-1"
                                />
                              </span>
                            </div>
                          </div>
                          <div className="flex justify-between items-center py-1">
                            <p className="font-semibold max-w-[225px] sm:max-w-full">
                              {t("shipping-vat")}
                            </p>
                            <div className="flex items-center">
                              <p className="text-gray-600 text-[17px] font-semibold">
                                {(
                                  (Number(totalShipping) / 100) *
                                  Number(vat)
                                ).toFixed(2)}
                              </p>
                              <span className="inline-block ">
                                <Image
                                  src={"/images/ryial.svg"}
                                  alt="currancy icon"
                                  width={12}
                                  height={12}
                                  className="ms-1"
                                />
                              </span>
                            </div>
                          </div>
                        </>
                      )}
                      {Number(discount) > 0 && (
                        <div className="flex justify-between items-center py-1">
                          <p className="font-semibold max-w-[225px] sm:max-w-full">
                            {t("discount-code")}
                          </p>
                          <div className="flex items-center">
                            <p
                              className={`text-gray-600 text-[17px] font-semibold ${
                                Number(discount) > 0 ? "me-2" : ""
                              }`}
                            >
                              {promoCodeValue}
                            </p>
                          </div>
                        </div>
                      )}
                      <div className="flex justify-between items-center py-1">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("discount")}
                        </p>
                        <div className="flex items-center">
                          <p
                            className={`text-gray-600 text-[17px] font-semibold ${
                              discountType === 2 ? "me-1" : ""
                            }`}
                          >
                            {Number(discount).toFixed(2)}
                          </p>
                          {discountType === 1 ? (
                            <span className="inline-block ">
                              <Image
                                src={"/images/ryial.svg"}
                                alt="currancy icon"
                                width={12}
                                height={12}
                                className="ms-1"
                              />
                            </span>
                          ) : (
                            "%"
                          )}
                          {/* {t("sar")}  */}
                        </div>
                      </div>
                      <div className="flex justify-between items-center py-4 border-solid border-t-[1px]">
                        <p className="font-semibold max-w-[225px] sm:max-w-full">
                          {t("total-price")}
                        </p>
                        <div className="flex items-center">
                          <p className="font-semibold text-[17px]">
                            {discountType === 1
                              ? (
                                  (Number(discount) > Number(totalIncludeVat)
                                    ? 0
                                    : Number(totalIncludeVat) -
                                      Number(discount)) +
                                  (pickupMethod === 2
                                    ? Number(totalShipping) +
                                      (Number(totalShipping) / 100) *
                                        Number(vat)
                                    : 0)
                                ).toFixed(2)
                              : (
                                  Number(totalIncludeVat) -
                                  (Number(totalIncludeVat) * Number(discount)) /
                                    100 +
                                  (pickupMethod === 2
                                    ? Number(totalShipping) +
                                      (Number(totalShipping) / 100) *
                                        Number(vat)
                                    : 0)
                                ).toFixed(2)}
                            {/* {t("sar")} */}{" "}
                          </p>
                          <span className="inline-block ">
                            <Image
                              src={"/images/ryial.svg"}
                              alt="currancy icon"
                              width={12}
                              height={12}
                              className="ms-1"
                            />
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                {branchesDisplayAction === "auto_select" ? null : (
                  <div className="mt-[30px] w-full lg:w-[calc(55%-15px)]">
                    <p className=" text-[18px] pb-4 md:text-[20px] font-semibold">
                      {t("suggested-pharmacies")}
                    </p>
                    {closesPharmacies?.length > 0 ? (
                      closesPharmacies?.map((item: any, index: any) => (
                        <>
                          <div
                            key={index}
                            className={`cursor-pointer py-[10px] mb-[20px] border ${
                              addressContinueBtnClicked && !branchId
                                ? "border-custom-red"
                                : "border-[#03B89E]"
                            }  rounded-lg bg-custom-gradient`}
                          >
                            <div className="flex justify-between items-center ">
                              <div className="flex items-center px-[10px] md:px-[20px]">
                                <Radio
                                  type="primary"
                                  checked={branchId === item?.branch_id}
                                  onChange={() => {
                                    dispatch(
                                      fetchBranchIdSuccess(item?.branch_id),
                                    );
                                    setDeliveryType(item?.delivery_type);
                                    const selectedBranch =
                                      closesPharmacies?.filter(
                                        (element: any) =>
                                          element?.branch_id ===
                                          item?.branch_id,
                                      )[0];
                                    console.log(selectedBranch);
                                    // setSelectedBranch(selectedBranch);
                                    dispatch(
                                      fetchSelectedBranch(selectedBranch),
                                    );
                                  }}
                                />

                                <div className="flex gap-2">
                                  <p className="text-[16] font-[400] text-[#424242]">
                                    {item?.branch_name}
                                  </p>
                                </div>
                              </div>
                              <p className="pe-4">
                                {availabilityObj[`${item?.availability}`]}
                              </p>
                            </div>
                            <div className="flex justify-between ps-[30px] md:ps-[40px]  pe-[15px] md:pe-[15px] text-[12px] md:text-[14px]">
                              {pickupMethod === 2 ? (
                                item?.delivery_type === "internal" ? (
                                  <p className="text-primary">
                                    {" "}
                                    {t("internal-delivery")}
                                  </p>
                                ) : (
                                  <p className="text-yellow-500">
                                    {t("smsa-delivery")}
                                  </p>
                                )
                              ) : null}
                              <p className=" text-[14px] md:text-[16px]">
                                {item?.branch_address && (
                                  <a
                                    href={`https://www.google.com/maps?q=${item?.branch_lat},${item?.branch_lng}`}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex items-center gap-1 text-[13px] text-gray-500 hover:text-primary transition-colors"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <IoLocationSharp className="text-gray-400 text-[14px] shrink-0" />
                                    <span className="line-clamp-1">
                                      {item?.branch_address}
                                    </span>
                                  </a>
                                )}
                              </p>
                              {item?.distance ? (
                                <p>
                                  {item?.distance
                                    ? `  ${item?.distance.toFixed(3)} `
                                    : ""}{" "}
                                  {t("km")}
                                </p>
                              ) : null}
                            </div>

                            {/* <p className="text-[16] font-[400] text-[#424242] px-[20px] mb-[10px]">
                              {item?.branch_name}
                            </p> */}
                            {+item?.availability !== 1 && (
                              <div className="px-4 py-2">
                                <Collapse
                                  items={[
                                    {
                                      key: "1",
                                      label: (
                                        <p className="font-bold text-primary text-center md:text-[20px]">
                                          {t("check-product-availability")}
                                        </p>
                                      ),
                                      children: (
                                        <div className="max-h-[400px] p-4 overflow-y-auto">
                                          {item?.product_availability.map(
                                            (item: availableProduct) => (
                                              <div
                                                className="flex justify-between items-center"
                                                key={item?.product_id}
                                              >
                                                <div
                                                  // key={item?.product_id}
                                                  className="flex items-center justify-start my-2"
                                                >
                                                  <div className="px-4 py-2 bg-[#F1FBFF]">
                                                    {/* <img
                                                        src={
                                                          item?.product_image
                                                        }
                                                        className="h-[60px] w-[40px]  mx-auto "
                                                      /> */}
                                                    <Image
                                                      src={item?.product_image}
                                                      width={40}
                                                      height={60}
                                                      alt=""
                                                      loading="lazy"
                                                      className="mx-auto"
                                                    />
                                                  </div>
                                                  <div className="px-2">
                                                    <p>
                                                      {
                                                        availabilityObj[
                                                          `${item?.is_available}`
                                                        ]
                                                      }
                                                    </p>
                                                    <p>{item?.product_name}</p>
                                                    {/* <div className="flex items-center">
                                                      <p>
                                                        {item?.product_price}{" "}
                                                      </p>
                                                      <span className="inline-block ">
                                                        <Image
                                                          src={
                                                            "/images/ryial.svg"
                                                          }
                                                          alt="currancy icon"
                                                          width={12}
                                                          height={12}
                                                          className="ms-1"
                                                        />
                                                      </span>
                                                     
                                                    </div> */}
                                                    {/* Price Section */}
                                                    <div className="flex py-1 mb-2">
                                                      {Number(
                                                        item?.offer_details
                                                          ?.offer_price,
                                                      ) &&
                                                      Number(
                                                        item?.offer_details
                                                          ?.offer_price,
                                                      ) <
                                                        Number(
                                                          item?.product_price,
                                                        ) ? (
                                                        <div className="flex items-center">
                                                          <p className="text-secondary ms-2">
                                                            {Number(
                                                              item
                                                                ?.offer_details
                                                                ?.offer_price,
                                                            ).toFixed(2)}
                                                          </p>
                                                          <span className="inline-block">
                                                            <Image
                                                              src={
                                                                "/images/ryial.svg"
                                                              }
                                                              alt="currency icon"
                                                              width={12}
                                                              height={12}
                                                              className="ms-1"
                                                            />
                                                          </span>
                                                        </div>
                                                      ) : null}
                                                      <div className="flex items-center">
                                                        <p
                                                          className={`${
                                                            Number(
                                                              item
                                                                ?.offer_details
                                                                ?.offer_price,
                                                            ) &&
                                                            Number(
                                                              item
                                                                ?.offer_details
                                                                ?.offer_price,
                                                            ) <
                                                              Number(
                                                                item?.product_price,
                                                              )
                                                              ? "line-through text-gray-400"
                                                              : "text-secondary"
                                                          } ms-2`}
                                                        >
                                                          {Number(
                                                            item?.product_price,
                                                          ).toFixed(2)}
                                                        </p>
                                                        <span className="inline-block">
                                                          <Image
                                                            src={
                                                              "/images/ryial.svg"
                                                            }
                                                            alt="currency icon"
                                                            width={12}
                                                            height={12}
                                                            className="ms-1"
                                                          />
                                                        </span>
                                                      </div>
                                                    </div>
                                                  </div>
                                                </div>
                                                {+item?.is_available !== 1 ? (
                                                  <p className="min-w-[55px]">
                                                    {t("qty")}
                                                    <span
                                                      className={`${
                                                        +item?.is_available ===
                                                        3
                                                          ? "text-custom-red"
                                                          : "text-primary"
                                                      }  ms-1`}
                                                    >
                                                      {item?.required_quantity}/
                                                      {item?.available_quantity}
                                                    </span>
                                                  </p>
                                                ) : (
                                                  <p className="min-w-[55px]">
                                                    {t("qty")}
                                                    <span
                                                      className={`text-primary ms-1`}
                                                    >
                                                      {item?.required_quantity}/
                                                      {item?.required_quantity}
                                                    </span>
                                                  </p>
                                                )}
                                              </div>
                                            ),
                                          )}
                                        </div>
                                      ),
                                    },
                                  ]}
                                />
                              </div>
                            )}
                          </div>
                        </>
                      ))
                    ) : (
                      <p>{t("no-pharmacies-found")}</p>
                    )}
                  </div>
                )}
              </>
            )}
            {showAddressPart === "list" && (
              <>
                <p className=" text-[18px] py-2 md:text-[20px] font-semibold">
                  {t("address-list")}
                </p>
                <p className=" text-[16px] py-2 md:text-[18px] text-[#8C8C8C]">
                  {t("select-specific-address-to-use-it")}
                </p>
                {[1, 2].map((item, index) => (
                  <div
                    key={index}
                    className={`border-solid border-[1px] ${
                      index === checkedAddress
                        ? "border-primary"
                        : "border-gray-200"
                    } rounded-[5px] mt-4`}
                  >
                    <div className="border-solid border-b-[1px] border-gray-200">
                      <div className="p-4">
                        <Radio
                          checked={index === checkedAddress}
                          value={1}
                          onClick={() => setCheckedAddress(index)}
                        >
                          {" "}
                          Address 1{" "}
                        </Radio>
                      </div>
                    </div>
                    <div className="p-4">
                      <div className="flex items-center py-2">
                        <p className="w-[30%] md:w-[15%]">{t("governate")}</p>{" "}
                        <p className="w-[70%] md:w-[85%] text-gray-500">
                          : AlGharbia
                        </p>
                      </div>
                      <div className="flex items-center py-2">
                        <p className="w-[30%] md:w-[15%]">{t("city")}</p>{" "}
                        <p className="w-[70%] md:w-[85%] text-gray-500">
                          : Almahala al kubra
                        </p>
                      </div>
                      <div className="flex items-center py-2">
                        <p className="w-[30%] md:w-[15%]">
                          {t("more-details")}
                        </p>{" "}
                        <p className="w-[70%] md:w-[85%] text-gray-500">
                          :Almahala al kubra
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
                <div className="flex justify-center items-center">
                  <Button
                    onClick={() => setShowAddressPart("new")}
                    className="!text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[16px] lg:text-[20px] font-semibold mx-2 my-[50px] min-h-[50px] w-[48%] sm:w-[200px] md:w-[30%] !rounded-[12px]"
                  >
                    {t("add-address")}{" "}
                    <FaArrowRightLong
                      className={`text-[16px] lg:text-[20px] mx-1 ${
                        locale === "ar" ? "rotate-180" : ""
                      }`}
                    />
                  </Button>
                  <Button
                    //onClick={() => setStepper(2)}
                    className="!text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[16px] lg:text-[20px] font-semibold mx-2 my-[50px] min-h-[50px] w-[48%] sm:w-[200px] md:w-[30%] !rounded-[12px]"
                  >
                    {t("confirm")}{" "}
                    <FaArrowRightLong
                      className={`text-[16px] lg:text-[20px] mx-1 ${
                        locale === "ar" ? "rotate-180" : ""
                      }`}
                    />
                  </Button>
                </div>
              </>
            )}
            {showAddressPart === "new" && (
              <>
                <p className=" text-[18px] py-2 md:text-[20px] font-semibold">
                  {t("add-new-address")}
                </p>
                <div className="add-address flex flex-col w-full sm:w-[70%] md:w-[50%]">
                  <Select
                    showSearch
                    placeholder={t("governate")}
                    optionFilterProp="label"
                    onChange={onChange}
                    onSearch={onSearch}
                    className="my-2"
                    options={[
                      {
                        value: "Gharbia",
                        label: "Gharbia",
                      },
                      {
                        value: "Cairo",
                        label: "Cairo",
                      },
                      {
                        value: "Alex",
                        label: "Alex",
                      },
                    ]}
                  />
                  <Select
                    showSearch
                    placeholder={t("city")}
                    optionFilterProp="label"
                    onChange={onChange}
                    onSearch={onSearch}
                    className="my-2"
                    options={[
                      {
                        value: "Mahalla",
                        label: "Mahalla",
                      },
                      {
                        value: "Tanta",
                        label: "Tanta",
                      },
                      {
                        value: "Mansoura",
                        label: "Mansoura",
                      },
                    ]}
                  />
                  <TextArea
                    className="my-2"
                    rows={4}
                    placeholder={t("write-your-address-details")}
                    maxLength={6}
                  />
                  <div className="flex items-center py-2 text-primary underline w-fit cursor-pointer">
                    <IoLocationSharp className="text-primary text-[20px]" />
                    {t("pick-your-location")}
                  </div>
                </div>
                <hr className="text-black w-full my-2 bg-black" />
                <Checkbox
                  onChange={onCheckBoxChange}
                  className="py-2 text-gray-500"
                >
                  {t("use-title-default-title")}
                </Checkbox>
                <Button
                  // onClick={() => setStepper(2)}
                  className="!text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[16px] lg:text-[20px] font-semibold mx-auto my-[50px] min-h-[50px] w-[200px] md:w-[30%] !rounded-[12px]"
                >
                  {t("save-address")}{" "}
                  <FaArrowRightLong className="text-[16px] lg:text-[20px] mx-1" />
                </Button>
              </>
            )}
          </div>
        </div>
      ) : (
        <div className="flex flex-col justify-center items-center mt-[200px]">
          <Image
            src="/images/no-address.png"
            alt="no-address"
            width={200}
            height={300}
            style={{ objectFit: "contain" }}
            className="mb-[20px]"
          />
          <p className="text-secondary p-2 text-[20px] md:text-[30px] font-bold">
            {t(`didnot-add-address-yet`)}
          </p>
          <p className="text-secondary p-2 text-[16px] md:text-[20px] ">
            {t("no-address-found")}
          </p>
          <button
            onClick={() => {
              dispatch(setEditingAddress(0, "", "", "", 0, 0));
              dispatch(addEditAddress("add"));
              router.push(`/${locale}/address/new-address`);
            }}
            className="!text-white my-[20px] !bg-primary !border-none !outline-none flex justify-center items-center text-[16px] lg:text-[20px] font-semibold mx-auto  min-h-[50px] w-[200px] md:w-[300px] !rounded-[12px]"
          >
            <Link
              href={`/${locale}/products`}
              className="flex gap-2 items-center"
              locale={false}
              // onClick={() => setStepper(2)}
              // className="!text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[50px] min-h-[50px] w-[50%] md:w-[30%] !rounded-[12px]"
            >
              {t("add-address")}{" "}
              <FaArrowRightLong
                className={`text-[16px] lg:text-[20px] mx-1 ${
                  locale === "ar" ? "rotate-180" : ""
                }`}
              />
            </Link>
          </button>
        </div>
      )}
    </>
  );
}
