"use client";
import React, { useState, useEffect } from "react";
import axios from "../../../utils/axios-config";
import { Steps, Radio, Button, message, Modal, Spin } from "antd";
import { IoIosArrowBack } from "react-icons/io";
import Image from "next/image";
import type { RadioChangeEvent } from "antd";
import { useTranslations, useLocale } from "next-intl";
import { HiOutlineShoppingBag } from "react-icons/hi2";
import { LoadingOutlined } from "@ant-design/icons";
import { CiLocationOn } from "react-icons/ci";
import { useMutation } from "@tanstack/react-query";
import { IoBagCheckOutline } from "react-icons/io5";
import { useRouter } from "next/navigation";
import {
  FETCH_CART_SUCCESS,
  FETCH_CART_LENGTH,
  fetchPrescriptionSuccess,
  fetchMinOrderPrice,
} from "@/store/cart/actions";
import { saveProduct } from "@/store/product/actions";
import Link from "next/link";
import { useDispatch, useSelector } from "react-redux";
import { IoIosCloseCircleOutline } from "react-icons/io";
import {
  fetchBranchIdSuccess,
  fetchSelectedBranch,
} from "@/store/address/actions";
import { fetchAddressIdSuccess } from "@/store/address/actions";
import { GiConfirmed } from "react-icons/gi";
import { fetchCartLength, fetchCartSuccess } from "@/store/cart/actions";
import { FaArrowRightLong } from "react-icons/fa6";
import CartAddress from "@/components/cart-address";
import {
  fetchPickupMethod,
  fetchPromoCode,
  fetchPromoCodeId,
  fetchPromoCodePrice,
  fetchDiscount,
  fetchCouponType,
} from "@/store/cart/actions";
import Prescriptions from "@/components/prescriptions";
import NoItem from "@/components/no-items";
import { set } from "zod";

const cartProductSkeleton = (
  <div className="container mx-auto px-4 pt-[200px]">
    <div className="flex justify-center gap-6">
      <div className="w-[60%] p-4">
        <div className="w-full h-20 my-2 me-2 bg-gray-300 rounded-md animate-pulse"></div>
        <div className="w-full h-20 my-2 bg-gray-300 rounded-md animate-pulse"></div>
        <div className="w-full h-20 my-2 bg-gray-300 rounded-md animate-pulse"></div>
        <div className="w-full h-20 my-2 bg-gray-300 rounded-md animate-pulse"></div>
      </div>
      <div className="w-[40%] p-4">
        <div className="w-full h-80 me-2 bg-gray-300 rounded-md animate-pulse"></div>
      </div>
    </div>
  </div>
);

export default function Cart() {
  const {
    pickupMethod,
    prescriptions,
    promoCode,
    promoCodePrice,
    promoCodeId,
    discountVal,
    couponType,
  } = useSelector((state: { Cart: any }) => state.Cart);
  const { addresses, addressId, branchId, selectedBranch } = useSelector(
    (state: { Address: any }) => state.Address,
  );
  const locale = useLocale();

  const [stepper, setStepper] = useState(0);
  const [cartParts, setCartParts] = useState("products");
  const [cartItems, setCartItems] = useState<any>([]);
  const [vatRatio, setVatRatio] = useState(0);
  const [vat, setVat] = useState(0);
  const [shippingType, setShippingType] = useState<any>(undefined);
  const [deletedProductId, setDeletedProductId] = useState<any>(undefined);
  const [quantityStatus, setQuantitystatus] = useState("");
  const [updateQuantityLoading, setUpdateQuantityLoading] = useState(false);
  const [orderSuccessOpen, setOrderSuccessOpen] = useState(false);
  const [addressContinueBtnClicked, setAddressContinueBtnClicked] =
    useState(false);
  const [branchesDisplayAction, setBranchesDisplayAction] = useState("");
  const [pharmaciesArrLength, setPharmaciesArrLength] = useState(0);
  const [damagedProducts, setDamagedProducts] = useState<any[]>([]);
  const [damagedProductsMessage, setDamagedProductsMessage] = useState("");
  const [damagedProductsModalOpen, setDamagedProductsModalOpen] =
    useState(false);
  const [deliveryType, setDeliveryType] = useState("");
  const [confirmOrder, setConfirmOrder] = useState(false);
  const [activateLoading, setActivateLoading] = useState(false);
  const [cartLoading, setCartLoading] = useState(true);
  const [itemsTotalPrice, setItemsTotalPrice] = useState(0);
  const [totalIncludeVat, setTotalIncludeVat] = useState(0);
  const [totalExcludeVat, setTotalExcludeVat] = useState(0);
  const [paymentPartTotalIncludeVat, setPaymentPartTotalIncludeVat] =
    useState(0);
  const [paymentPartTotalExcludeVat, setPaymentPartTotalExcludeVat] =
    useState(0);
  const [totalShipping, setTotalShipping] = useState(0);
  const [hasPrescription, setHasPrescription] = useState<any>(undefined);
  const [isValidRoute, setIsValidRoute] = useState(false);
  const [cashDeliveryFees, setCashDeliveryFees] = useState(0);
  const [discount, setDiscount] = useState<any>(discountVal);
  const [discountType, setDiscountType] = useState(couponType);
  const [isAnimating, setIsAnimating] = useState(false);
  const [promoCodeValue, setPromoCodeValue] = useState<any>(promoCode);
  const [paymentMethod, setPaymentMethod] = useState<any>(undefined);
  const [paymentMethods, setPaymentMethods] = useState<
    { id: number; name: string; enabled: number }[]
  >([]);
  const [confirmPaymentLoading, setConfirmPaymentLoading] = useState(false);
  const [updateCartClicked, setUpdateCartClicked] = useState(false);
  const dispatch = useDispatch();
  const router = useRouter();

  useEffect(() => {
    dispatch(fetchBranchIdSuccess(undefined));
    dispatch(fetchSelectedBranch(undefined));
    dispatch(fetchAddressIdSuccess(undefined));
  }, []);

  useEffect(() => {
    const fetchPaymentMethods = async () => {
      try {
        const response = await axios.get("/payment-methods");
        setPaymentMethods(response?.data?.data || []);
      } catch (err) {
        console.error("Failed to fetch payment methods", err);
      }
    };
    fetchPaymentMethods();
  }, []);

  const isPaymentEnabled = (name: string) => {
    const method = paymentMethods.find((m) => m.name === name);
    return method ? method.enabled === 1 : true;
  };

  useEffect(() => {
    //console.log("branchId", branchId,addressId)
    const checkValidateRouteFunc = async () => {
      let x = "";
      if (Number(pickupMethod) === 2) {
        x = "?delivery_method=2";
      }
      try {
        const response = await axios.get(
          `/route-validation/address/${addressId}/branch/${branchId}${x}`,
        );

        const { data } = await response;
        console.log("validation Route", data.data);
        setShippingType(data?.data?.is_remote_shipping);
        setTotalShipping(
          data?.data?.shipping_price ? Number(data?.data?.shipping_price) : 0,
        );
        if (response?.data?.status || response?.status === 200) {
          setIsValidRoute(true);
          //setDamagedProductsObj(data);
        } else {
          // console.log("validation Route failed");
          setIsValidRoute(false);
          if (response?.data?.errors?.damaged_products) {
            setDamagedProducts(response?.data?.errors?.damaged_products);
            setDamagedProductsMessage(response?.data?.message);
            setDamagedProductsModalOpen(true);
          } else {
            message.error(response?.data?.message);
            // console.log("damaged products", response?.data?.errors?.damaged_products);
          }

          // message.error(data?.message );
        }
      } catch (err: any) {
        //console.error("Error validating route:", err);
        // console.log("errrrrrrrr", err);
        if (!err?.response?.data?.errors) {
          message.error(err?.response?.data?.message);
        } else {
          setDamagedProducts(err?.response?.data?.errors?.damaged_products);
          setDamagedProductsMessage(err?.response?.data?.message);
          setDamagedProductsModalOpen(true);
        }
        // setDamagedProductsModalOpen(true);
        setIsValidRoute(false);
        message.error(err?.message);
      }
    };
    if (addressId && branchId && cartParts === "address") {
      checkValidateRouteFunc();
    }
  }, [branchId, cartParts]);

  const t = useTranslations();
  /// fetch cart
  const fetchCartData = async () => {
    setCartLoading(true);
    try {
      const response = await axios.get("/my-cart");
      const data = response?.data?.data;

      setVatRatio(data?.vat_ratio);
      setVat(Number(data?.vat));
      setCartItems([...data?.products]);
      const requiredPresc = data?.products.some(
        (item: any) => +item?.requires_prescription !== 0,
      );
      setCashDeliveryFees(data?.cash_delivery_fee);
      // console.log("my cart", data);
      // setTotalShipping(data.delivery_price ? Number(data.delivery_price) : 0);
      setHasPrescription(requiredPresc);
      if (!requiredPresc) {
        dispatch(fetchPrescriptionSuccess([]));
      }
      const totalPrice = +eval(
        data?.products
          ?.map((item: any) => {
            // item?.offer_price && Number(item?.offer_price) < Number(item?.price)
            //   ? Number(item?.offer_price) * Number(item?.quantity)
            //   : Number(item?.price) * Number(item?.quantity)
            if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity === 0
            ) {
              return Number(item?.offer_price) * Number(item?.quantity);
            } else if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity > 0
            ) {
              // const buyAndFree =
              //   Number(item?.offer_free_quantity) +
              //   Number(item?.offer_buy_quantity);
              const offerQuantity =
                Math.floor(
                  Number(item?.quantity) /
                    (Number(item?.offer_free_quantity) +
                      Number(item?.offer_buy_quantity)),
                ) * Number(item?.offer_free_quantity);

              const total =
                Number(item?.quantity) >= offerQuantity && offerQuantity > 0
                  ? item?.offer_discount_type === 1
                    ? offerQuantity *
                        (Number(item?.offer_price) -
                          Number(item?.offer_discount_value)) +
                      // (Number(offerQuantity)*Number(item?.offer_discount_value))
                      (Number(item?.quantity) - offerQuantity) *
                        Number(item?.offer_price)
                    : offerQuantity * Number(item?.offer_price) -
                      (offerQuantity *
                        Number(item?.offer_price) *
                        Number(item?.offer_discount_value)) /
                        100 +
                      (Number(item?.quantity) - offerQuantity) *
                        Number(item?.offer_price)
                  : Number(item?.quantity) * Number(item?.offer_price);
              // const totalWithDiscount = Number(item?.quantity) >= buyAndFree ?
              return total;
            } else {
              return Number(item?.price) * Number(item?.quantity);
            }
          })
          .join("+"),
      )?.toFixed(2);

      const totalPriceExcVat = +eval(
        data?.products
          ?.map((item: any) => {
            if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              Number(item?.offer_free_quantity) === 0
            ) {
              const total =
                Number(item?.offer_price) / (100 + Number(item?.tax));
              return total * 100 * Number(item?.quantity);
            } else if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity > 0
            ) {
              // const buyAndFree =
              //   Number(item?.offer_free_quantity) +
              //   Number(item?.offer_buy_quantity);
              const offerQuantity =
                Math.floor(
                  Number(item?.quantity) /
                    (Number(item?.offer_free_quantity) +
                      Number(item?.offer_buy_quantity)),
                ) * Number(item?.offer_free_quantity);
              const itemExcVat =
                (Number(item?.offer_price) / (100 + Number(item?.tax))) * 100;
              const total =
                Number(item?.quantity) >= offerQuantity && offerQuantity > 0
                  ? item?.offer_discount_type === 1
                    ? // offerQuantity * Number(itemExcVat) -
                      //   Number(item?.offer_discount_value)
                      offerQuantity *
                        (Number(itemExcVat) -
                          Number(item?.offer_discount_value)) +
                      (Number(item?.quantity) - offerQuantity) *
                        Number(itemExcVat)
                    : offerQuantity * Number(itemExcVat) -
                      (offerQuantity *
                        Number(itemExcVat) *
                        Number(item?.offer_discount_value)) /
                        100 +
                      (Number(item?.quantity) - offerQuantity) *
                        Number(itemExcVat)
                  : Number(item?.quantity) * Number(itemExcVat);
              // const totalWithDiscount = Number(item?.quantity) >= buyAndFree ?
              return total;
            } else {
              return Number(item?.price_before) * Number(item?.quantity);
            }
          })
          .join("+"),
      )?.toFixed(2);

      if (!totalPrice) {
        setItemsTotalPrice(0);
      } else {
        setItemsTotalPrice(totalPrice ? Number(totalPrice) : 0);
        setTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
        setTotalExcludeVat(totalPriceExcVat ? Number(totalPriceExcVat) : 0);
        setPaymentPartTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
        setPaymentPartTotalExcludeVat(
          totalPriceExcVat ? Number(totalPriceExcVat) : 0,
        );
      }
      dispatch({ type: FETCH_CART_SUCCESS, payload: data?.products });
      dispatch({ type: FETCH_CART_LENGTH, payload: data?.products?.length });
      setCartLoading(false);
    } catch (err: any) {
      message.error(err?.message);
      setCartLoading(false);
    }
  };
  useEffect(() => {
    setDiscount(discountVal);
    setDiscountType(couponType);
  }, [couponType, discountVal]);
  useEffect(() => {
    setPromoCodeValue(promoCode);
  }, [promoCode]);
  useEffect(() => {
    localStorage.removeItem("paymentHtml");
    fetchCartData();
  }, []);
  useEffect(() => {
    dispatch(fetchPrescriptionSuccess([]));
  }, []);
  const onRecieveOrderWayChange = (e: RadioChangeEvent) => {
    dispatch(fetchPickupMethod(e.target.value));
    dispatch(fetchAddressIdSuccess(undefined));
    dispatch(fetchBranchIdSuccess(undefined));
    dispatch(fetchSelectedBranch(undefined));
  };

  const calculateTotals = (products: any[], vatRatio: number) => {
    const totalPrice = +eval(
      products
        ?.map((item: any) => {
          // item?.offer_price && Number(item?.offer_price) < Number(item?.price)
          //   ? Number(item?.offer_price) * Number(item?.quantity)
          //   : Number(item?.price) * Number(item?.quantity)
          if (
            Number(item?.offer_price) &&
            Number(item?.offer_price) <= Number(item?.price) &&
            item?.offer_free_quantity === 0
          ) {
            return Number(item?.offer_price) * Number(item?.quantity);
          } else if (
            Number(item?.offer_price) &&
            Number(item?.offer_price) <= Number(item?.price) &&
            item?.offer_free_quantity > 0
          ) {
            // const buyAndFree =
            //   Number(item?.offer_free_quantity) +
            //   Number(item?.offer_buy_quantity);
            const offerQuantity =
              Math.floor(
                Number(item?.quantity) /
                  (Number(item?.offer_free_quantity) +
                    Number(item?.offer_buy_quantity)),
              ) * Number(item?.offer_free_quantity);

            const total =
              Number(item?.quantity) >= offerQuantity && offerQuantity > 0
                ? item?.offer_discount_type === 1
                  ? offerQuantity *
                      (Number(item?.offer_price) -
                        Number(item?.offer_discount_value)) +
                    // (Number(offerQuantity)*Number(item?.offer_discount_value))
                    (Number(item?.quantity) - offerQuantity) *
                      Number(item?.offer_price)
                  : offerQuantity * Number(item?.offer_price) -
                    (offerQuantity *
                      Number(item?.offer_price) *
                      Number(item?.offer_discount_value)) /
                      100 +
                    (Number(item?.quantity) - offerQuantity) *
                      Number(item?.offer_price)
                : Number(item?.quantity) * Number(item?.offer_price);
            // const totalWithDiscount = Number(item?.quantity) >= buyAndFree ?
            return total;
          } else {
            return Number(item?.price) * Number(item?.quantity);
          }
        })
        .join("+"),
    )?.toFixed(2);

    const totalPriceExcVat = +eval(
      products
        ?.map((item: any) => {
          if (
            Number(item?.offer_price) &&
            Number(item?.offer_price) <= Number(item?.price) &&
            Number(item?.offer_free_quantity) === 0
          ) {
            const total = Number(item?.offer_price) / (100 + Number(item?.tax));
            return total * 100 * Number(item?.quantity);
          } else if (
            Number(item?.offer_price) &&
            Number(item?.offer_price) <= Number(item?.price) &&
            item?.offer_free_quantity > 0
          ) {
            // const buyAndFree =
            //   Number(item?.offer_free_quantity) +
            //   Number(item?.offer_buy_quantity);
            const offerQuantity =
              Math.floor(
                Number(item?.quantity) /
                  (Number(item?.offer_free_quantity) +
                    Number(item?.offer_buy_quantity)),
              ) * Number(item?.offer_free_quantity);
            const itemExcVat =
              (Number(item?.offer_price) / (100 + Number(item?.tax))) * 100;
            const total =
              Number(item?.quantity) >= offerQuantity && offerQuantity > 0
                ? item?.offer_discount_type === 1
                  ? // offerQuantity * Number(itemExcVat) -
                    //   Number(item?.offer_discount_value)
                    offerQuantity *
                      (Number(itemExcVat) -
                        Number(item?.offer_discount_value)) +
                    (Number(item?.quantity) - offerQuantity) *
                      Number(itemExcVat)
                  : offerQuantity * Number(itemExcVat) -
                    (offerQuantity *
                      Number(itemExcVat) *
                      Number(item?.offer_discount_value)) /
                      100 +
                    (Number(item?.quantity) - offerQuantity) *
                      Number(itemExcVat)
                : Number(item?.quantity) * Number(itemExcVat);
            // const totalWithDiscount = Number(item?.quantity) >= buyAndFree ?
            return total;
          } else {
            return Number(item?.price_before) * Number(item?.quantity);
          }
        })
        .join("+"),
    )?.toFixed(2);

    setItemsTotalPrice(totalPrice ? Number(totalPrice) : 0);
    setTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
    setTotalExcludeVat(totalPriceExcVat ? Number(totalPriceExcVat) : 0);
    setPaymentPartTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
    setPaymentPartTotalExcludeVat(
      totalPriceExcVat ? Number(totalPriceExcVat) : 0,
    );
    if (Number(totalPrice) < Number(promoCodePrice)) {
      setPromoCodeValue("");
      dispatch(fetchPromoCodeId(undefined));

      dispatch(fetchPromoCode(undefined));
      dispatch(fetchDiscount(0));
      dispatch(fetchPromoCodePrice(undefined));
    }
  };

  const updateQuantity = async (id: number, newQuantity: number) => {
    try {
      setUpdateCartClicked(true);
      setUpdateQuantityLoading(true);
      const response = await axios.post("/update-cart", {
        products: [{ product_id: id, quantity: newQuantity }],
      });

      setCartItems((prev: any) => {
        const updatedCart = prev.map((item: any) =>
          item.id === id ? { ...item, quantity: newQuantity } : item,
        );
        calculateTotals(updatedCart, vatRatio);

        return updatedCart;
      });
      message.success(response?.data?.message);
      dispatch(fetchBranchIdSuccess(undefined));
      dispatch(fetchSelectedBranch(undefined));
    } catch (err: any) {
      message.error(err?.message);
      if (quantityStatus === "increase") {
        setCartItems((prev: any) =>
          prev.map((item: any) =>
            item?.id === id ? { ...item, quantity: item?.quantity - 1 } : item,
          ),
        );
      } else {
        setCartItems((prev: any) =>
          prev.map((item: any) =>
            item.id === id ? { ...item, quantity: item.quantity + 1 } : item,
          ),
        );
      }
    } finally {
      setUpdateQuantityLoading(false);
    }
  };

  // //// delete product
  const deleteProductMutation = useMutation({
    mutationFn: (values) => axios["post"](`remove-from-cart/${values}`),
    onSuccess: (res) => {
      message.success(res?.data?.message);

      // fetchCartData();
      dispatch(fetchBranchIdSuccess(undefined));
      dispatch(fetchSelectedBranch(undefined));
      ////
      const filteredCartItems = cartItems.filter(
        (item: any) => item.id !== deletedProductId,
      );
      setCartItems(filteredCartItems);
      const requiredPresc = filteredCartItems?.some(
        (item: any) => +item?.requires_prescription !== 0,
      );

      setHasPrescription(requiredPresc);
      if (!requiredPresc) {
        dispatch(fetchPrescriptionSuccess([]));
      }
      // const totalPrice = +eval(
      //   filteredCartItems
      //     ?.map((item: any) =>
      //       item?.offer_price && Number(item?.offer_price) < Number(item?.price)
      //         ? Number(item?.offer_price) * Number(item?.quantity)
      //         : Number(item?.price) * Number(item?.quantity)
      //     )
      //     .join("+")
      // )?.toFixed(2);

      // const totalPriceExcVat = +eval(
      //   filteredCartItems
      //     ?.map((item: any) => {
      //       if (
      //         Number(item?.offer_price) &&
      //         Number(item?.offer_price) < Number(item?.price)
      //       ) {
      //         const total =
      //           Number(item?.offer_price) / (100 + Number(item?.tax));
      //         return total * 100 * Number(item?.quantity);
      //       } else {
      //         return Number(item?.price_before) * Number(item?.quantity);
      //       }
      //     })
      //     .join("+")
      // )?.toFixed(2);
      const totalPrice = +eval(
        filteredCartItems
          ?.map((item: any) => {
            if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity === 0
            ) {
              return Number(item?.offer_price) * Number(item?.quantity);
            } else if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity > 0
            ) {
              const offerQuantity =
                Math.floor(
                  Number(item?.quantity) /
                    (Number(item?.offer_free_quantity) +
                      Number(item?.offer_buy_quantity)),
                ) * Number(item?.offer_free_quantity);

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

              return total;
            } else {
              return Number(item?.price) * Number(item?.quantity);
            }
          })
          .join("+"),
      )?.toFixed(2);

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

              return total;
            } else {
              return Number(item?.price_before) * Number(item?.quantity);
            }
          })
          .join("+"),
      )?.toFixed(2);

      if (!totalPrice) {
        setItemsTotalPrice(0);
      } else {
        setItemsTotalPrice(totalPrice ? Number(totalPrice) : 0);
        setTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
        setTotalExcludeVat(totalPriceExcVat ? Number(totalPriceExcVat) : 0);
        setPaymentPartTotalIncludeVat(totalPrice ? Number(totalPrice) : 0);
        setPaymentPartTotalExcludeVat(
          totalPriceExcVat ? Number(totalPriceExcVat) : 0,
        );
      }
      dispatch({ type: FETCH_CART_SUCCESS, payload: filteredCartItems });
      dispatch({ type: FETCH_CART_LENGTH, payload: filteredCartItems?.length });
      ////
    },
    onError: (err) => {
      const {
        status,
        data: { message },
      } = (err as any).response;

      message.error(message, {
        position: "top-center",
        duration: 3000,
      });
    },
  });

  const activateCodeFunc = async () => {
    // console.log('activate')
    try {
      setActivateLoading(true);
      const response = await axios.post(`activate-code/${promoCodeValue}`);
      const data = await response?.data?.data;
      dispatch(fetchMinOrderPrice(Number(data?.min_order_price)));
      if (Number(totalIncludeVat) >= Number(data?.min_order_price)) {
        setDiscount(data?.coupon_value);
        dispatch(
          fetchDiscount(data.coupon_value ? Number(data.coupon_value) : 0),
        );
        if (data.coupon_type === 1) {
          dispatch(fetchCouponType(1));

          setDiscountType(1);
        } else {
          dispatch(fetchCouponType(2));
          setDiscountType(2);
          //setItemsTotalPrice(totalIncludeVat - ((totalIncludeVat * data.coupon_value) / 100))
        }
        // console.log("Coupon applied:", data);
        dispatch(fetchPromoCodeId(data?.coupon_id));
        dispatch(fetchPromoCode(promoCodeValue));
        dispatch(fetchPromoCodePrice(data?.min_order_price));
        setActivateLoading(false);
        message.success(response?.data?.message);
      } else {
        setPromoCodeValue("");
        setActivateLoading(false);
        message.warning(
          `${t("total-order-price")} ${data?.min_order_price} ${t("sar")}`,
        );
      }
    } catch (err: any) {
      //dispatch(fetchPromoCode(undefined));
      setActivateLoading(false);
      message.error(err?.message);
    }
  };

  const confirmPayment = async (id: string, paymentTab: Window | null) => {
    try {
      const redirectUrl = `/${locale}/reorder`;
      const response = await axios.post(
        `confirm-payment/${id}?payment_method=${paymentMethod}&redirect_url=${encodeURIComponent(redirectUrl)}`,
      );
      const { payment_id, html } = await response?.data?.data;

      if (payment_id && html) {
        localStorage.setItem("paymentHtml", html);

        if (paymentTab) {
          paymentTab.location.href = `/payment?checkoutId=${payment_id}`;
        }
      }

      router.push(`/${locale}/`);
      dispatch(fetchCartLength(0));
      message.success(response?.data?.message);
    } catch (err) {
      if (paymentTab) {
        paymentTab.close();
      }
    }
  };

  const confirmCashPayment = async (id: string) => {
    try {
      const redirectUrl = `/${locale}/reorder`;
      const response = await axios.post(
        `confirm-payment/${id}?payment_method=${paymentMethod}&redirect_url=${encodeURIComponent(redirectUrl)}`,
      );
      // const { payment_id, html } = response?.data?.data;

      // if (payment_id && html) {
      //   sessionStorage.setItem("paymentHtml", html);

      //   if (paymentTab) {
      //     paymentTab.location.href = `/payment?checkoutId=${payment_id}`;
      //   }
      //}

      //setTimeout(()=>{
      router.push(`/${locale}/`);
      dispatch(fetchCartLength(0));
      //  },3000)
      message.success(response?.data?.message);
    } catch (err: any) {
      message.error(err?.message);
    }
  };
  // // ///// checkout function
  const checkoutMutation = useMutation({
    mutationFn: (values: FormData) =>
      axios.post("orders", values, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        // headers: {
        //   "Accept-Language": `${locale === "en" ? "en-US" : "ar-SA"}`,
        // },
      }),
  });

  // const checkoutFunc = () => {
  //   if (!paymentMethod) {
  //     message.warning(t("please-select-paymnet-method"));
  //   } else {
  //     setConfirmOrder(true);
  //     const formData = new FormData();

  //     if (prescriptions?.length > 0) {
  //       prescriptions.forEach((file: any) => {
  //         const fileObj = file.originFileObj || file; // Use originFileObj if available

  //         if (fileObj instanceof Blob) {
  //           // Ensure it's a valid Blob
  //           formData.append("prescriptions[]", fileObj, file.name);
  //         } else {
  //           console.error("Invalid file object:", file);
  //         }
  //       });
  //     }

  //     formData.append("branch_id", branchId);
  //     formData.append("address_id", addressId);
  //     formData.append("payment_method", paymentMethod);
  //     formData.append("delivery_method", pickupMethod);

  //     checkoutMutation.mutate(formData);
  //   }
  // };

  // Checkout Function
  const checkoutFunc = () => {
    if (!paymentMethod) {
      message.warning(t("please-select-paymnet-method"));
      return;
    }

    setConfirmOrder(true);

    const formData = new FormData();

    if (prescriptions.length > 0) {
      // console.log("prescriptions", prescriptions);
      prescriptions.forEach((file: any, index: any) => {
        const fileToAppend = file.originFileObj ? file.originFileObj : file; // Handle both cases
        //  console.log("fileToAppend", fileToAppend);
        formData.append(`prescriptions[]`, fileToAppend);
      });
    }

    formData.append("branch_id", branchId);
    formData.append("address_id", addressId);
    formData.append("payment_method", paymentMethod);
    formData.append("delivery_method", pickupMethod);
    if (promoCodeId) {
      formData.append("coupon", promoCodeValue);
    }

    const paymentTab = window.open("", "_blank");
    if (paymentTab) {
      paymentTab.document.write("<h3>Loading payment, please wait.... </h3>");
    } else {
      alert("Popup blocked! Please allow popups for this site.");
      return;
    }

    checkoutMutation.mutate(formData, {
      onSuccess: (res) => {
        // console.log("checkout", res.data);
        const data = res?.data?.data;
        if (data?.confirm_payment !== 3) {
          confirmPayment(data?.order_id, paymentTab);
        } else {
          router.push(`/${locale}/orders`);
        }
        message.success(res.data.message);
        setOrderSuccessOpen(true);
        dispatch(fetchPromoCodeId(undefined));
        dispatch(fetchPromoCode(undefined));
        dispatch(fetchDiscount(0));
        dispatch(fetchPromoCodePrice(undefined));
        setPromoCodeValue("");
        setPaymentMethod(undefined);
        dispatch(fetchPrescriptionSuccess([]));
      },
    });
  };

  //// checkout cash
  const checkoutCashFunc = () => {
    if (!paymentMethod) {
      message.warning(t("please-select-paymnet-method"));
      return;
    }

    setConfirmOrder(true);
    const formData = new FormData();

    if (prescriptions?.length > 0) {
      prescriptions.forEach((file: any) => {
        const fileObj = file.originFileObj || file;
        if (fileObj instanceof Blob) {
          formData.append("prescriptions[]", fileObj, file.name);
        } else {
          console.error("Invalid file object:", file);
        }
      });
    }

    formData.append("branch_id", branchId);
    formData.append("address_id", addressId);
    formData.append("payment_method", paymentMethod);
    formData.append("delivery_method", pickupMethod);
    if (promoCodeId) {
      formData.append("coupon", promoCodeValue);
    }

    checkoutMutation.mutate(formData, {
      onSuccess: (res) => {
        // console.log("checkout", res.data);
        const data = res?.data?.data;

        // confirmCashPayment(data?.order_id);
        // } else {
        //router.push("/");
        dispatch(fetchCartLength(0));
        dispatch(fetchCartSuccess([]));
        // }
        // message.success(res?.data?.message);
        setOrderSuccessOpen(true);
        setPaymentMethod(undefined);
        dispatch(fetchPromoCodeId(undefined));
        dispatch(fetchPromoCode(undefined));
        dispatch(fetchDiscount(0));
        dispatch(fetchPromoCodePrice(undefined));
        // setPromoCodeValue(undefined);
        dispatch(fetchPrescriptionSuccess([]));
      },
      onError: (err) => {
        message.error(err.message);
      },
    });
  };
  useEffect(() => {
    if (updateCartClicked) {
      // const totalPrice = cartItems?.reduce(
      //   (acc: any, item: any) =>
      //     acc +
      //     (item?.offer_price && Number(item?.offer_price) < Number(item?.price)
      //       ? Number(item?.offer_price)
      //       : Number(item?.price)) *
      //       Number(item?.quantity),
      //   0
      // );
      const totalPrice = +eval(
        cartItems
          ?.map((item: any) => {
            // item?.offer_price && Number(item?.offer_price) < Number(item?.price)
            //   ? Number(item?.offer_price) * Number(item?.quantity)
            //   : Number(item?.price) * Number(item?.quantity)
            if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity === 0
            ) {
              return Number(item?.offer_price) * Number(item?.quantity);
            } else if (
              Number(item?.offer_price) &&
              Number(item?.offer_price) <= Number(item?.price) &&
              item?.offer_free_quantity > 0
            ) {
              // const buyAndFree =
              //   Number(item?.offer_free_quantity) +
              //   Number(item?.offer_buy_quantity);
              const offerQuantity =
                Math.floor(
                  Number(item?.quantity) /
                    (Number(item?.offer_free_quantity) +
                      Number(item?.offer_buy_quantity)),
                ) * Number(item?.offer_free_quantity);

              const total =
                Number(item?.quantity) >= offerQuantity
                  ? item?.offer_discount_type === 1
                    ? offerQuantity * Number(item?.offer_price) -
                      Number(item?.offer_discount_value) +
                      (Number(item?.quantity) - offerQuantity) *
                        Number(item?.offer_price)
                    : offerQuantity * Number(item?.offer_price) -
                      (offerQuantity *
                        Number(item?.offer_price) *
                        Number(item?.offer_discount_value)) /
                        100 +
                      (Number(item?.quantity) - offerQuantity) *
                        Number(item?.offer_price)
                  : Number(item?.quantity) * Number(item?.offer_price);
              // const totalWithDiscount = Number(item?.quantity) >= buyAndFree ?
              return total;
            } else {
              return Number(item?.price) * Number(item?.quantity);
            }
          })
          .join("+"),
      )?.toFixed(2);

      if (Number(totalPrice) < Number(promoCodePrice)) {
        console.log("updated", totalPrice, promoCodePrice);
        if (promoCodeId) {
          message.warning(
            `${t("promo-code-limit")} ${promoCodePrice} ${t("sar")}`,
          );
        }
        setPromoCodeValue("");
        dispatch(fetchPromoCodeId(undefined));
        // dispatch(fetchPromoCode(undefined));
        // dispatch(fetchPromoCodePrice(undefined));
        // message.warning(
        //   `${t("promo-code-limit")} ${promoCodePrice} ${t("sar")}`
        // );
      }
    }
  }, [cartItems]);

  const offerDiscreption = (
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number,
  ) => {
    return (
      <div className="text-[12px]">
        {freeQuantity === 0 ? (
          <div
            className={`${
              locale === "en" ? "flex-row-reverse" : "flex-row"
            } flex items-center`}
          >
            <span className={`${locale === "en" ? "ms-2" : "me-2"}`}>
              {t("off")}{" "}
            </span>

            {discountValue}
            {discountType === 1 ? (
              <Image
                src={"/images/ryial.svg"}
                alt="currancy icon"
                width={12}
                height={12}
                className="ms-1"
              />
            ) : (
              "%"
            )}
          </div>
        ) : discountValue === 100 && discountType === 2 ? (
          ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")}
            </>
          </>
        )}
      </div>
    );
  };
  const offerCalcLabel = (
    price: number,
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number,
  ) => {
    return (
      <div className="flex items-center">
        <span className="me-1  text-[12px]">{t("offer-price")}</span>
        {freeQuantity === 0 ? (
          <></>
        ) : discountValue === 100 && discountType === 2 ? (
          // ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
          <div className="flex items-center gap-1">
            <p className="text-white">
              {(Number(buyQuantity) * Number(price)).toFixed(2)}
            </p>
            <p className="text-white opacity-70 line-through">
              {(
                (Number(buyQuantity) + Number(freeQuantity)) *
                Number(price)
              ).toFixed(2)}
            </p>
          </div>
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {/* {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")} */}
              <div className="flex items-center gap-1">
                <p className="text-white">
                  {(Number(discountType) === 1
                    ? Number(buyQuantity) * Number(price) +
                      Number(freeQuantity) *
                        (Number(price) - Number(discountValue))
                    : Number(buyQuantity) * Number(price) +
                      Number(freeQuantity) *
                        ((Number(price) / 100) * (100 - Number(discountValue)))
                  ).toFixed(2)}
                </p>
                <p className="text-white opacity-70 line-through">
                  {(
                    (Number(freeQuantity) + Number(buyQuantity)) *
                    Number(price)
                  ).toFixed(2)}
                </p>
              </div>
            </>
          </>
        )}
      </div>
    );
  };

  if (cartLoading) {
    return <>{cartProductSkeleton}</>;
  }
  return (
    <>
      {cartItems?.length === 0 ? (
        <div className="container mx-auto pt-[200px]">
          <NoItem />
          <Link
            href={`/${locale}/products`}
            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("browsing-now")}{" "}
            <FaArrowRightLong className="text-[24px] mx-2" />
          </Link>
        </div>
      ) : (
        <div className=" ">
          <div className="bg-[#F2F4F5] p-4">
            <div className="container mx-auto px-4">
              <div className="w-full lg:w-[50%]">
                <Steps
                  current={stepper}
                  items={[
                    {
                      title: t("shopping-cart"),
                      icon: <HiOutlineShoppingBag />,
                    },
                    {
                      title: t("address"),
                      icon: <CiLocationOn />,
                    },
                    {
                      title: t("checkout"),
                      icon: <IoBagCheckOutline />,
                    },
                  ]}
                />
              </div>
            </div>
          </div>
          <div className="container mx-auto px-4 py-[50px] ">
            {cartParts === "products" && (
              <>
                <div className="flex flex-col items-center lg:flex-row lg:items-start justify-between">
                  <div className="w-full lg:w-[calc(60%-15px)]">
                    <div className="rounded-[10px] bg-custom-gradient p-4 border-solid border-[1px] border-primary">
                      <p className="pb-2">{t("select-your-delivery-method")}</p>
                      <Radio.Group
                        onChange={onRecieveOrderWayChange}
                        value={pickupMethod}
                      >
                        <Radio value={1}>{t("pharmacy-pickup")}</Radio>
                        <Radio value={2}>{t("home-delivery")}</Radio>
                      </Radio.Group>
                    </div>
                    <div className="rounded-[10px] bg-custom-gradient my-4 p-2 border-solid border-[1px] border-primary">
                      <p className=" text-third text-[18px] md:text-[20px]">
                        {t("order-items")}
                      </p>
                    </div>
                    <div>
                      {cartLoading ? (
                        <div>{t("loading-products")}</div>
                      ) : (
                        cartItems?.map((item: any, index: any) => (
                          <div
                            key={index}
                            className="cart-product flex justify-between items-center py-4 border-solid border-b-[1px] border-gray-300"
                          >
                            <div className="flex items-center justify-start ">
                              <div className="min-w-[100px] sm:min-w-[125px] flex items-center justify-start">
                                {deletedProductId === item?.id &&
                                deleteProductMutation?.isPending ? (
                                  <Spin
                                    className={`w-[20px] h-[20px] sm:text-[25px] sm:w-[25px] sm:h-[25px] mx-1 text-gray-400`}
                                    indicator={<LoadingOutlined spin />}
                                    size="default"
                                  />
                                ) : (
                                  <IoIosCloseCircleOutline
                                    className={`w-[20px] h-[20px] sm:text-[25px] sm:w-[25px] sm:h-[25px] mx-1  ${
                                      deleteProductMutation?.isPending
                                        ? "text-gray-400 pointer-events-none"
                                        : "text-[#ff0000] cursor-pointer"
                                    }`}
                                    onClick={() => {
                                      setDeletedProductId(item?.id);
                                      deleteProductMutation.mutate(item?.id);
                                    }}
                                  />
                                )}
                                <div className="p-2 bg-[#F1FBFF]">
                                  <div
                                    onClick={() => dispatch(saveProduct(item))}
                                    className="w-[80px] h-[80px] relative  "
                                  >
                                    {/* <img
                                    src={item?.image}
                                    className="h-[60px] w-[60px] sm:w-[80px] sm:h-[80px] mx-auto "
                                  /> */}

                                    <Image
                                      src={item?.image}
                                      fill
                                      alt=""
                                      className="object-contain"
                                    />
                                    <Link
                                      href={`/${locale}/products/${(item?.name)
                                        .replace(
                                          /[^a-zA-Z0-9\u0600-\u06FF]+/g,
                                          "-",
                                        )
                                        .replace(/^-+|-+$/g, "")
                                        .toLowerCase()}?id=${item.id}`}
                                      locale={false}
                                      className="absolute w-full  h-full top-0 left-0 z-[40] "
                                    ></Link>
                                  </div>
                                </div>
                              </div>
                              <div className="px-2">
                                <div
                                  className="relative"
                                  onClick={() => dispatch(saveProduct(item))}
                                >
                                  {/* {item?.offer_title && (
                                    <p className=" z-[40] bg-red-500 text-white rounded-full text-xs  py-1 px-3 text-wrap w-fit">
                                      {item?.offer_title}
                                    </p>
                                  )} */}
                                  {item?.offer_title && (
                                    <p className=" z-[40] flex gap-1 items-center justify-center flex-wrap w-fit bg-red-500 text-white  rounded-e-full text-sm   px-1 text-wrap opacity-80 ">
                                      {offerDiscreption(
                                        item?.offer_buy_quantity,
                                        item?.offer_free_quantity,
                                        item?.offer_discount_type,
                                        item?.offer_discount_value,
                                      )}
                                    </p>
                                  )}
                                  <Link
                                    href={`/${locale}/products/${(item?.name)
                                      .replace(
                                        /[^a-zA-Z0-9\u0600-\u06FF]+/g,
                                        "-",
                                      )
                                      .replace(/^-+|-+$/g, "")
                                      .toLowerCase()}?id=${item.id}`}
                                    locale={false}
                                    className="absolute w-full  h-full top-0 left-0 z-[40] "
                                  ></Link>
                                  <p className="text-third line-clamp-1">
                                    {item?.name}
                                  </p>
                                  {Number(item?.offer_free_quantity) > 0 ? (
                                    <div className="text-sm w-fit bg-primary bg-opacity-50 px-1  rounded-e-full">
                                      {offerCalcLabel(
                                        item?.price,
                                        item?.offer_buy_quantity,
                                        item?.offer_free_quantity,
                                        item?.offer_discount_type,
                                        item?.offer_discount_value,
                                      )}
                                    </div>
                                  ) : null}
                                </div>
                                {item?.requires_prescription === 1 && (
                                  <div className="flex items-center justify-center mt-1 gap-1 px-2 py-1  w-fit h-fit bg-[#FBC43A] text-white rounded-[5px]">
                                    <Image
                                      src={"/images/prescription-icon.svg"}
                                      alt="prescription icon"
                                      width={18}
                                      height={18}
                                    />
                                    <p className="text-[12px]">
                                      {t("prescription")}
                                    </p>
                                  </div>
                                )}
                                <div className="flex sm:hidden w-fit justify-between items-center text-gray-400">
                                  (
                                  <div className="flex items-center gap-1 justify-between ">
                                    <div className="flex flex-wrap items-center justify-center text-[12px] sm:text-[13px] text-gray-400 ">
                                      <p className="text-[12px]">
                                        {t("exc-vat")}
                                      </p>
                                      <div className="flex justify-between items-center">
                                        <span className="text-primary mx-1">
                                          {Number(item?.price_before).toFixed(
                                            2,
                                          )}
                                        </span>{" "}
                                        <Image
                                          src={"/images/ryial.svg"}
                                          alt="currancy icon"
                                          width={12}
                                          height={12}
                                          className=""
                                        />
                                      </div>
                                    </div>
                                    <div className="w-[1px] h-[15px] bg-gray-400" />
                                    {/* <p className="text-gray-400 text-[12px] sm:text-[13px] ms-1">
                                      {t("Vat")}
                                      <span className="text-primary ms-1">
                                        {item.tax}%
                                      </span>
                                    </p> */}
                                    <div className="flex flex-wrap text-[12px] sm:text-[13px] text-gray-400 ">
                                      <p className="!m-0 !p-0 text-[12px]">
                                        {t("Vat")}
                                      </p>
                                      <span className="text-primary mx-1">
                                        {item.tax}%
                                      </span>{" "}
                                    </div>
                                  </div>
                                  )
                                </div>
                              </div>
                            </div>
                            <div className="text-center ">
                              <div className="flex justify-center items-center gap-2">
                                <div className="flex justify-between items-center">
                                  {Number(item?.offer_price) &&
                                  Number(item?.offer_price) <
                                    Number(item?.price) ? (
                                    <>
                                      <p className="text-[18px] md:text-[20px] text-primary text-center">
                                        {item?.offer_price}
                                      </p>
                                      <span className="inline-block ">
                                        <Image
                                          src={"/images/ryial.svg"}
                                          alt="currancy icon"
                                          width={12}
                                          height={12}
                                          className="ms-1"
                                        />
                                      </span>
                                    </>
                                  ) : null}
                                </div>
                                <div className="flex justify-between items-center">
                                  {/* {!item?.offer_price ||
                                  Number(item?.offer_price) <=
                                    Number(item?.price) ? ( */}
                                  <>
                                    <p
                                      className={`text-[18px] md:text-[20px] ${
                                        Number(item?.offer_price) &&
                                        Number(item?.offer_price) <
                                          Number(item?.price)
                                          ? "line-through text-gray-400"
                                          : "text-primary"
                                      } text-center`}
                                    >
                                      {item?.price}
                                    </p>
                                    <span className="inline-block ">
                                      <Image
                                        src={"/images/ryial.svg"}
                                        alt="currancy icon"
                                        width={12}
                                        height={12}
                                        className="ms-1"
                                      />
                                    </span>
                                  </>
                                  {/* ) : null} */}
                                </div>
                              </div>

                              {/* <div className="hidden sm:flex justify-between items-center text-gray-400">
                                (
                                <div className="flex flex-wrap items-center flex-grow text-[13px] text-gray-400 border-e-[1px] border-solid border-gray-400">
                                  <p>{t("exc-vat")}</p>
                                  <div className="flex items-center">
                                    <span className="text-primary ms-1">
                                      {Number(item?.price_before).toFixed(2)}
                                    </span>{" "}
                                    <Image
                                      src={"/images/ryial.svg"}
                                      alt="currancy icon"
                                      width={25}
                                      height={25}
                                    />
                                  </div>
                                </div>
                                <p className="text-gray-400 text-[13px] ms-1">
                                  {t("Vat")}
                                  <span className="text-primary ms-1">
                                    {item.tax}%
                                  </span>
                                </p>
                                )
                              </div> */}
                              <div className="sm:flex hidden w-fit justify-between items-center text-gray-400">
                                (
                                <div className="flex items-center justify-between ">
                                  <div className="flex   text-[12px] sm:text-[13px] text-gray-400 ">
                                    <p className="flex items-center text-[12px]">
                                      {t("exc-vat")}
                                    </p>
                                    <div className="flex justify-between items-center">
                                      <span className="text-primary mx-1">
                                        {item?.offer_price &&
                                        Number(item?.offer_price) <
                                          Number(item?.price)
                                          ? (
                                              (Number(item?.offer_price) /
                                                (100 + Number(item?.tax))) *
                                              100
                                            ).toFixed(2)
                                          : Number(item?.price_before).toFixed(
                                              2,
                                            )}
                                      </span>{" "}
                                      <Image
                                        src={"/images/ryial.svg"}
                                        alt="currancy icon"
                                        width={12}
                                        height={12}
                                        className="me-1"
                                      />
                                    </div>
                                  </div>
                                  <div className="w-[1px] h-[15px] bg-gray-400" />
                                  <p className="text-gray-400 text-[12px]  ms-1">
                                    {t("Vat")}
                                    <span className="text-primary ms-1">
                                      {item.tax}%
                                    </span>
                                  </p>
                                </div>
                                )
                              </div>
                              {item?.offer_price && (
                                <div className="flex justify-center items-center">
                                  {/* <p className="line-through text-third text-center text-[14px] py-1">
                                    {item?.offer_price} +
                                    (
                                      <span className="inline-block mx-1">
                                        <Image
                                          src={"/images/ryial.svg"}
                                          alt="currancy icon"
                                          width={25}
                                          height={25}
                                        />
                                      </span>
                                    )
                                  </p> */}
                                  {/* <p className="text-[#ff0000] p-2 text-center text-[14px] ">
                                    {item?.offer_title}
                                  </p> */}
                                </div>
                              )}

                              <div className="rounded-[72px] flex  min-w-[90px] w-full sm:min-w-[200px] ">
                                <Button
                                  className={`${
                                    updateQuantityLoading
                                      ? "pointer-events-none !bg-secondary/50"
                                      : "pointer-events-auto !bg-secondary"
                                  } !border-none !outline-none p-2 min-h-[30px] w-[25%] rounded-s-[72px] !text-white font-semibold text-[20px]`}
                                  onClick={() =>
                                    updateQuantity(item.id, item.quantity - 1)
                                  }
                                  disabled={
                                    updateQuantityLoading || item.quantity <= 1
                                  }
                                >
                                  -
                                </Button>
                                <p className="min-h-[30px] w-[40%] sm:w-[50%] flex justify-center items-center bg-[#EDF4F6] text-secondary text-center">
                                  {item?.quantity}
                                </p>
                                <Button
                                  className={`${
                                    updateQuantityLoading
                                      ? "pointer-events-none !bg-secondary/50"
                                      : "pointer-events-auto !bg-secondary"
                                  } !border-none !outline-none p-2 min-h-[30px] w-[25%] rounded-e-[72px] !text-white font-semibold text-[20px]`}
                                  onClick={() =>
                                    updateQuantity(item.id, item.quantity + 1)
                                  }
                                  disabled={updateQuantityLoading}
                                >
                                  +
                                </Button>
                              </div>
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                  <div className="lg:ms-4 w-full lg:w-[calc(40%-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">
                            {cartItems?.length}
                          </span>
                          {cartItems?.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">
                          <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={13}
                              height={12}
                              className="ms-1"
                            />
                          </span>
                        </div>
                      </div>
                      <div className="flex justify-between gap-2 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">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {Number(totalIncludeVat).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 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)}
                          </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>
                          ) : (
                            "%"
                          )}
                        </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 className="mt-[20px] p-4 border-solid border-[1px] rounded-[10px] border-primary flex justify-between items-center">
                      <input
                        className="border-none outline-none flex-grow"
                        readOnly={promoCode ? true : false}
                        value={promoCodeValue}
                        onChange={(e) => setPromoCodeValue(e.target.value)}
                        placeholder={t("enter-promo-code")}
                      />
                      {!promoCode ? (
                        <Button
                          disabled={promoCodeValue ? false : true}
                          loading={activateLoading}
                          className="!text-primary !bg-transparent text-[16px] ms-5 !border-none !outline-none shadow-none"
                          onClick={() => activateCodeFunc()}
                        >
                          {t("activate")}
                        </Button>
                      ) : (
                        <IoIosCloseCircleOutline
                          className="text-primary text-[24px] ms-5 cursor-pointer"
                          onClick={() => {
                            setPromoCodeValue("");
                            setDiscount(0);
                            dispatch(fetchDiscount(0));
                            // dispatch(fetchCouponType(1))
                            // setDiscountType(1)
                            dispatch(fetchPromoCodeId(undefined));
                            dispatch(fetchPromoCode(""));
                            dispatch(fetchPromoCodePrice(undefined));
                          }}
                        />
                      )}
                    </div>
                  </div>
                </div>

                <Button
                  onClick={() => {
                    setStepper(1);
                    setCartParts("address");
                  }}
                  className="!text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[18px] lg:text-[20px] font-semibold mx-auto my-[70px] min-h-[50px] w-[200px] md:w-[30%] !rounded-[12px]"
                >
                  {t("continue")}{" "}
                  <FaArrowRightLong
                    className={`text-[18px] lg:text-[20px] mx-2 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />
                </Button>
              </>
            )}
            {cartParts === "address" && (
              <>
                <div
                  className={`hover:text-primary hover:bg-white border-[1px] border-solid border-primary  flex items-center justify-center w-fit py-1 px-2 cursor-pointer rounded-[10px] bg-primary text-white rotate-0 `}
                  onClick={() => {
                    // router.back();
                    // window.scrollTo(0, 0);
                    setCartParts("products");
                    setIsValidRoute(false);
                  }}
                >
                  <IoIosArrowBack
                    className={`text-[24px] md:text-[30px] me-1 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />{" "}
                  <span className="inline-block me-2">{t("back")}</span>
                </div>
                <CartAddress
                  itemsTotalPrice={totalIncludeVat}
                  itemsTotalPriceExcVat={totalExcludeVat}
                  discount={discount}
                  branchesDisplayAction={branchesDisplayAction}
                  setBranchesDisplayAction={setBranchesDisplayAction}
                  totalShipping={totalShipping}
                  setPharmaciesArrLength={setPharmaciesArrLength}
                  setTotalExcludeVat={setTotalExcludeVat}
                  setTotalIncludeVat={setTotalIncludeVat}
                  deliveryType={deliveryType}
                  setDeliveryType={setDeliveryType}
                  setPaymentPartTotalExcludeVat={setPaymentPartTotalExcludeVat}
                  setPaymentPartTotalIncludeVat={setPaymentPartTotalIncludeVat}
                  setHasPrescription={setHasPrescription}
                  setCartItems={setCartItems}
                  cartItems={cartItems}
                  discountType={discountType}
                  vatRatio={vatRatio}
                  promoCodeValue={promoCodeValue}
                  vat={vat}
                  addressContinueBtnClicked={addressContinueBtnClicked}
                  length={cartItems.length}
                />
                {addresses?.length > 0 && (
                  <Button
                    disabled={
                      pharmaciesArrLength === 0 ||
                      !addressId ||
                      !branchId ||
                      !isValidRoute ||
                      Number(paymentPartTotalIncludeVat) === 0
                    }
                    onClick={() => {
                      console.log("delivery_type", deliveryType);
                      if (!addressId) {
                        // setAddressContinueBtnClicked(true);
                        message.warning(t("select-address"));
                        return;
                      }
                      if (!branchId) {
                        setAddressContinueBtnClicked(true);
                        message.warning(t("select-branch"));
                        return;
                      }
                      if (hasPrescription) {
                        setCartParts("prescription");
                      } else {
                        setStepper(2);
                        setCartParts("payment");
                      }
                    }}
                    className={`!text-white ${
                      pharmaciesArrLength === 0 ||
                      !addressId ||
                      !branchId ||
                      !isValidRoute ||
                      Number(paymentPartTotalIncludeVat) === 0
                        ? "!bg-gray-400"
                        : "!bg-primary"
                    }  !border-none !outline-none flex justify-center items-center text-[18px] lg:text-[20px] font-semibold mx-auto my-[70px] min-h-[50px] w-[200px] md:w-[30%] !rounded-[12px]`}
                  >
                    {t("continue")}{" "}
                    <FaArrowRightLong
                      className={`text-[18px] lg:text-[20px] mx-2 ${
                        locale === "ar" ? "rotate-180" : ""
                      }`}
                    />
                  </Button>
                )}
              </>
            )}
            {cartParts === "prescription" && (
              <>
                <div
                  className={`hover:text-primary hover:bg-white border-[1px] border-solid border-primary   flex items-center justify-center w-fit mb-6 py-1 px-2 cursor-pointer rounded-[10px] bg-primary text-white rotate-0 `}
                  onClick={() => {
                    setCartParts("address");
                    setIsValidRoute(false);
                    console.log(branchId);
                  }}
                >
                  <IoIosArrowBack
                    className={`text-[24px] md:text-[30px] me-1 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />{" "}
                  <span className="inline-block me-2">{t("back")}</span>
                </div>
                {/* <p className="text-center pb-8 text-[18px] font-bold">
                  {t("upload-prescription")}
                </p> */}
                <Prescriptions products={cartItems} />
                <Button
                  disabled={prescriptions?.length === 0}
                  onClick={() => {
                    if (prescriptions?.length === 0) {
                      message.warning(t("please-upload-prescription"));
                      return;
                    }
                    setStepper(2);
                    setCartParts("payment");
                  }}
                  className={`!text-white ${
                    prescriptions?.length === 0 ? "!bg-gray-400" : "!bg-primary"
                  } !border-none !outline-none flex justify-center items-center text-[18px] lg:text-[20px] font-semibold mx-auto my-[70px] min-h-[50px] w-[200px] md:w-[30%] !rounded-[12px]`}
                >
                  {t("continue")}{" "}
                  <FaArrowRightLong
                    className={`text-[18px] lg:text-[20px] mx-2 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />
                </Button>
              </>
            )}
            {cartParts === "payment" && (
              <>
                <div
                  className={`hover:text-primary hover:bg-white border-[1px] border-solid border-primary  mb-6 flex items-center justify-center w-fit py-1 px-2 cursor-pointer rounded-[10px] bg-primary text-white rotate-0 `}
                  onClick={() => {
                    if (hasPrescription) {
                      setCartParts("prescription");
                    } else {
                      // setIsValidRoute(false);
                      setCartParts("address");
                    }
                  }}
                >
                  <IoIosArrowBack
                    className={`text-[24px] md:text-[30px] me-1 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />{" "}
                  <span className="inline-block me-2">{t("back")}</span>
                </div>
                <div className="flex flex-col items-center lg:flex-row lg:items-start justify-between">
                  <div className="w-full lg:w-[calc(60%-15px)]">
                    <div className="bg-custom-gradient border-[1px] border-solid border-primary rounded-[10px] p-4">
                      <div className="f py-1">
                        <p className="font-semibold text-[18px] md:text-[20px] py-2 text-primary">
                          {t("shopping-cart-summary")}
                        </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">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {/* {Number(totalExcludeVat).toFixed(2)} */}
                            {Number(paymentPartTotalExcludeVat).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">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {/* {Number(totalIncludeVat).toFixed(2)} */}
                            {Number(paymentPartTotalIncludeVat).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("vat-value")}
                        </p>
                        <div className="flex items-center">
                          <p className="text-gray-600 text-[17px] font-semibold">
                            {/* {(
                              Number(totalIncludeVat) - Number(totalExcludeVat)
                            ).toFixed(2)} */}
                            {Number(
                              paymentPartTotalIncludeVat -
                                paymentPartTotalExcludeVat,
                            ).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>
                      {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>
                        </>
                      )}

                      {pickupMethod === 2 &&
                        paymentMethod === 3 &&
                        Number(shippingType) !== 1 && (
                          <>
                            <div className="flex justify-between items-center py-1">
                              <p className="font-semibold max-w-[225px] sm:max-w-full">
                                {t("cash-on-delivery")}
                              </p>
                              <div className="flex items-center">
                                <p className="text-gray-600 text-[17px] font-semibold">
                                  {Number(cashDeliveryFees).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("cash-on-delivery-vat")}
                              </p>
                              <div className="flex items-center">
                                <p className="text-gray-600 text-[17px] font-semibold">
                                  {(
                                    (Number(cashDeliveryFees) / 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>
                          </>
                        )}
                      <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>
                          ) : (
                            "%"
                          )}
                        </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(paymentPartTotalIncludeVat)
                                    ? 0
                                    : Number(paymentPartTotalIncludeVat) -
                                      Number(discount)) +
                                  (pickupMethod === 2
                                    ? Number(totalShipping) +
                                      (Number(totalShipping) / 100) *
                                        Number(vat)
                                    : 0) +
                                  (pickupMethod === 2 &&
                                  paymentMethod === 3 &&
                                  Number(shippingType) !== 1
                                    ? Number(cashDeliveryFees) +
                                      (Number(cashDeliveryFees) / 100) *
                                        Number(vat)
                                    : 0)
                                ).toFixed(2)
                              : (
                                  Number(paymentPartTotalIncludeVat) -
                                  (Number(paymentPartTotalIncludeVat) *
                                    Number(discount)) /
                                    100 +
                                  (pickupMethod === 2
                                    ? Number(totalShipping) +
                                      (Number(totalShipping) / 100) *
                                        Number(vat)
                                    : 0) +
                                  (pickupMethod === 2 &&
                                  paymentMethod === 3 &&
                                  Number(shippingType) !== 1
                                    ? Number(cashDeliveryFees) +
                                      (Number(cashDeliveryFees) / 100) *
                                        Number(vat)
                                    : 0)
                                ).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>
                    {branchesDisplayAction === "auto_select" ? (
                      <div className="py-20px  text-[14px] md:text-[16px]">
                        {deliveryType === "internal" ? (
                          <div className="flex pt-1 gap-1">
                            <Image
                              src={"/images/logo-green.svg"}
                              alt="nav-icon"
                              width={100}
                              height={24}
                              priority
                            />
                            <p className="text-primary">
                              {" "}
                              {t("internal-delivery")} !
                            </p>
                          </div>
                        ) : (
                          <div className="flex pt-1 gap-1">
                            <Image
                              src={"/images/smsa-logo.svg"}
                              alt="nav-icon"
                              width={100}
                              height={24}
                              priority
                            />
                            <p className="text-[#400099]">
                              {t("smsa-delivery")} !
                            </p>
                          </div>
                        )}
                      </div>
                    ) : null}
                    <p className="pt-6 pb-0 text-[18px] md:text-[24px] font-bold">
                      {t("payment-method")}
                    </p>
                    <div className="flex py-6">
                      {isPaymentEnabled("credit") && (
                        <div
                          className={`
                          ${
                            paymentMethod === 1
                              ? "animate-scale-up border-solid border-[2px] border-primary"
                              : ""
                          }
                         cursor-pointer px-4 py-4 sm:px-8 rounded-[8px] shadow-md mx-2 bg-white flex justify-center items-center`}
                          onClick={() => {
                            setPaymentMethod(1);
                            setIsAnimating(true);
                            setTimeout(() => setIsAnimating(false), 500);
                          }}
                        >
                          {/* <img
                          src="/images/credit.png"
                          className="w-[70px] sm:w-[90px] "
                          alt="credit"
                        /> */}
                          <Image
                            src={"/images/visa.png"}
                            width={80}
                            height={80}
                            alt="credit"
                          />
                        </div>
                      )}
                      {isPaymentEnabled("mada") && (
                        <div
                          className={`${
                            paymentMethod === 2
                              ? "animate-scale-up border-solid border-[2px] border-primary"
                              : ""
                          }  cursor-pointer px-4 py-4 sm:px-8 rounded-[8px] shadow-md mx-2 bg-[#DEFFFC] flex justify-center items-center`}
                          onClick={() => {
                            setPaymentMethod(2);
                            setIsAnimating(true);
                            setTimeout(() => setIsAnimating(false), 500);
                          }}
                        >
                          {/* <img
                          src="/images/mada.png"
                          className="w-[70px] sm:w-[90px] "
                          alt="mada"
                        /> */}
                          <Image
                            src={"/images/mada.png"}
                            width={80}
                            height={80}
                            alt="mada"
                          />
                        </div>
                      )}
                      {Number(shippingType) === 1
                        ? null
                        : isPaymentEnabled("cash") && (
                            <div
                              className={`${
                                paymentMethod === 3
                                  ? "animate-scale-up border-solid border-[2px] border-primary"
                                  : ""
                              }  cursor-pointer px-4 py-4 sm:px-8 rounded-[8px] shadow-md mx-2 bg-white flex justify-center items-center`}
                              onClick={() => {
                                setPaymentMethod(3);
                                setIsAnimating(true);
                                setTimeout(() => setIsAnimating(false), 500);
                              }}
                            >
                              <Image
                                src={"/images/cash.png"}
                                width={80}
                                height={80}
                                alt="cash"
                              />
                            </div>
                          )}
                    </div>
                  </div>
                  <div className="w-full lg:w-[calc(40%-15px)]">
                    <div className="rounded-[10px] bg-custom-gradient mb-4 p-2 border-solid border-[1px] border-primary">
                      <p className="py-2 text-third text-[18px] md:text-[24px]">
                        {t("order-items")}
                      </p>
                    </div>
                    <div>
                      {/* {cartItems?.map((item: any, index: any) => ( */}
                      {cartItems
                        ?.filter(
                          (product: any) =>
                            selectedBranch?.product_availability?.find(
                              (item: any) => item.product_id === product.id,
                            )?.is_available === 1,
                        )
                        ?.map((item: any, index: any) => (
                          <div
                            key={index}
                            className="cart-product flex justify-between items-center py-4 border-solid border-b-[1px] border-gray-300"
                          >
                            <div className="flex items-center justify-start ">
                              <div className="flex items-center justify-center">
                                <span className="text-custom-red flex">
                                  {item.quantity}
                                </span>
                                <span className="text-custom-red mx-[2px]">
                                  x
                                </span>
                                <div className="p-2 bg-[#F1FBFF]">
                                  <div
                                    className="relative h-[80px] w-[80px]"
                                    onClick={() => dispatch(saveProduct(item))}
                                  >
                                    {/* <img
                                src={item?.image}
                                className="h-[80px] w-[95%]  mx-auto "
                              /> */}
                                    <Image
                                      src={item?.image}
                                      // width={75}
                                      // height={80}
                                      fill
                                      alt=""
                                      className="object-contain"
                                    />
                                    <Link
                                      href={`/${locale}/products/${(item?.name)
                                        .replace(
                                          /[^a-zA-Z0-9\u0600-\u06FF]+/g,
                                          "-",
                                        )
                                        .replace(/^-+|-+$/g, "")
                                        .toLowerCase()}?id=${item.id}`}
                                      locale={false}
                                      className="absolute w-full  h-full top-0 left-0 z-[40] "
                                    ></Link>
                                  </div>
                                </div>
                              </div>
                              <div className="px-2 w-[calc(100%-80px)]">
                                <div
                                  className="relative"
                                  onClick={() => dispatch(saveProduct(item))}
                                >
                                  {item?.offer_title && (
                                    <p className=" z-[40] flex gap-1 items-center justify-center flex-wrap w-fit bg-red-500 text-white rounded-e-full text-[12px] px-1 text-wrap opacity-80 ">
                                      {offerDiscreption(
                                        item?.offer_buy_quantity,
                                        item?.offer_free_quantity,
                                        item?.offer_discount_type,
                                        item?.offer_discount_value,
                                      )}
                                    </p>
                                  )}
                                  <Link
                                    href={`/${locale}/products/${(item?.name)
                                      .replace(
                                        /[^a-zA-Z0-9\u0600-\u06FF]+/g,
                                        "-",
                                      )
                                      .replace(/^-+|-+$/g, "")
                                      .toLowerCase()}?id=${item.id}`}
                                    locale={false}
                                    className="absolute w-full  h-full top-0 left-0 z-[40] "
                                  ></Link>
                                  <p className="text-third">{item?.name}</p>
                                  {Number(item?.offer_free_quantity) > 0 ? (
                                    <div className="text-sm w-fit bg-primary bg-opacity-70 px-1 py-1 rounded-e-full">
                                      {offerCalcLabel(
                                        item?.price,
                                        item?.offer_buy_quantity,
                                        item?.offer_free_quantity,
                                        item?.offer_discount_type,
                                        item?.offer_discount_value,
                                      )}
                                    </div>
                                  ) : null}
                                </div>
                                <p>
                                  {item?.specifications !== "null" &&
                                  item?.specifications
                                    ? item?.specifications
                                    : null}
                                </p>
                              </div>
                            </div>
                            <div className="text-center min-w-fit">
                              <div className="flex justify-center items-center gap-2">
                                <div className="flex justify-between items-center">
                                  {Number(item?.offer_price) &&
                                  Number(item?.offer_price) <
                                    Number(item?.price) ? (
                                    <>
                                      <p className="text-[18px] md:text-[20px] text-primary text-center">
                                        {item?.offer_price}
                                      </p>
                                      <span className="inline-block ">
                                        <Image
                                          src={"/images/ryial.svg"}
                                          alt="currancy icon"
                                          width={12}
                                          height={12}
                                          className="ms-1"
                                        />
                                      </span>
                                    </>
                                  ) : null}
                                </div>
                                <div className="flex justify-between items-center">
                                  {!item?.offer_price ||
                                  Number(item?.offer_price) <=
                                    Number(item?.price) ? (
                                    <>
                                      <p
                                        className={`text-[18px] md:text-[20px] ${
                                          Number(item?.offer_price) &&
                                          Number(item?.offer_price) <
                                            Number(item?.price)
                                            ? "line-through text-gray-400"
                                            : "text-primary"
                                        } text-center`}
                                      >
                                        {item?.price}
                                      </p>
                                      <span className="inline-block ">
                                        <Image
                                          src={"/images/ryial.svg"}
                                          alt="currancy icon"
                                          width={12}
                                          height={12}
                                          className="ms-1"
                                        />
                                      </span>
                                    </>
                                  ) : null}
                                </div>
                              </div>

                              {/* <div className="flex items-center">
                              <p className="text-[18px] md:text-[20px] text-primary text-center">
                                {item?.price}
                              </p>

                              <Image
                                src={"/images/ryial.svg"}
                                alt="currancy icon"
                                width={25}
                                height={25}
                              />

                              
                            </div> */}
                              {/* {item?.offer_price && (
                              <div className="flex justify-center items-center">
                                <div className="flex items-center">
                                  <p className="line-through text-third text-center text-[14px] py-1">
                                    {item.offer_price}
                                  </p>

                                  <span className="inline-block ">
                                    <Image
                                      src={"/images/ryial.svg"}
                                      alt="currancy icon"
                                      width={25}
                                      height={25}
                                    />
                                  </span>
                                </div>
                              </div>
                            )} */}
                            </div>
                          </div>
                        ))}
                    </div>
                  </div>
                </div>
                <Button
                  loading={checkoutMutation?.isPending || confirmPaymentLoading}
                  disabled={!paymentMethod}
                  onClick={() => {
                    // console.log("paymentMethod", paymentMethod)
                    if (paymentMethod === 3 || hasPrescription) {
                      checkoutCashFunc();
                    } else {
                      checkoutFunc();
                    }
                  }}
                  className={`!text-white ${
                    !paymentMethod ? "!bg-gray-400" : "!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("checkout")}{" "}
                  <FaArrowRightLong
                    className={`text-[24px] mx-2 ${
                      locale === "ar" ? "rotate-180" : ""
                    }`}
                  />
                </Button>
              </>
            )}

            <div className="py-4"></div>
          </div>
        </div>
      )}

      {/******confirm order modal pickup***** */}
      <Modal
        className="confirm-pickup"
        open={false}
        //onCancel={cancelConfirmModal}
        footer={null}
      >
        <div className="flex flex-col items-center py-8">
          <GiConfirmed className="text-[40px] md:text-[100px] text-primary" />
          <p className="font-bold pt-8 pb-2 text-[20px] md:text-[30px] text-gray-700">
            {t("well-done")}
          </p>
          <p className="font-semibold  text-[18px] md:text-[24px] text-gray-700">
            {t("your-order-confirmed-successfully")}
          </p>
          <Button
            // onClick={() => setStepper(2)}
            className="!text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto mt-[30px] mb-[10px] min-h-[50px] w-[70%]  !rounded-[12px]"
          >
            {t("review-the-order")}{" "}
            <FaArrowRightLong className="text-[24px] mx-2" />
          </Button>
          <Button
            //  onClick={() => setStepper(2)}
            className="!text-white !bg-primary !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[10px] min-h-[50px] w-[70%]  !rounded-[12px]"
          >
            {t("browse-for-more-items")}{" "}
            <FaArrowRightLong className="text-[24px] mx-2" />
          </Button>
        </div>
      </Modal>

      {/******confirm order modal delivery***** */}
      <Modal
        className="confirm-pickup"
        open={orderSuccessOpen}
        // onCancel={()=>setOrderSuccessOpen(false)}
        closeIcon={false}
        footer={null}
      >
        <div className="flex flex-col items-center py-8">
          {hasPrescription ? (
            <Image
              src={"/images/pay-success.png"}
              width={160}
              height={160}
              style={
                {
                  // objectFit:"contain"
                }
              }
              alt="image"
            />
          ) : (
            // <GiConfirmed className="text-[40px] md:text-[100px] text-primary" />
            <Image
              src={"/images/order-success.png"}
              width={160}
              height={160}
              style={
                {
                  // objectFit:"contain"
                }
              }
              alt="image"
            />
          )}
          {hasPrescription ? (
            <p className="font-bold pt-8 pb-2 text-[20px] md:text-[30px] text-gray-700">
              {t("order-successfully")}
            </p>
          ) : (
            <p className="font-semibold  text-[18px] md:text-[24px] text-gray-700">
              {t("your-order-confirmed-successfully")}
            </p>
          )}
          {hasPrescription && (
            <p className="text-[16px] md:text-[18px] text-gray-500 text-center">
              {t("check-prescription-message")}
            </p>
          )}
          <Button className="relative !text-primary !bg-white !border-primary !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto mt-[30px] mb-[10px] min-h-[50px] w-[70%]  !rounded-[12px]">
            <Link
              href={`/${locale}/orders`}
              locale={false}
              className="absolute w-full h-full top-0 left-0 flex justify-center items-center rtl:!text-[13px]"
            >
              {t("view-the-order")}{" "}
              <FaArrowRightLong className="text-[24px] mx-2" />
            </Link>
          </Button>
        </div>
      </Modal>

      {/******damaged Products modal***** */}
      <Modal
        className="confirm-pickup"
        open={damagedProductsModalOpen}
        onCancel={() => setDamagedProductsModalOpen(false)}
        //onCancel={cancelConfirmModal}
        footer={null}
      >
        <div className="flex flex-col items-center py-4">
          <p className="p-2 text-custom-red text-[16px]">
            {damagedProductsMessage}
          </p>
          <div className="w-full max-h-[300px] overflow-y-auto mt-[20px]">
            {damagedProducts?.map((item: any, index: any) => (
              <div
                key={index}
                className=" w-[90%] flex justify-between items-center p-2 rounded-md m-2 border-solid border-[1px] border-gray-300"
              >
                <div className="flex items-center justify-start ">
                  <div className="p-2 bg-[#F1FBFF]">
                    <div
                      className="relative  w-[80px] h-[80px]"
                      onClick={() => dispatch(saveProduct(item))}
                    >
                      <Image
                        src={item?.image}
                        fill
                        alt=""
                        //loading="lazy"
                        className="object-contain"
                      />
                      <Link
                        href={`/${locale}/products/${(item?.name)
                          .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                          .replace(/^-+|-+$/g, "")
                          .toLowerCase()}?id=${item.id}`}
                        locale={false}
                        className="absolute w-full  h-full top-0 left-0 z-[40] "
                      ></Link>
                    </div>
                  </div>
                  {/* <div className="px-2">
                        <p>{item?.name}</p>
                        <p>{item?.specifications}</p>
                      </div> */}
                  <div className="ps-4 ">
                    <div
                      className="relative"
                      onClick={() => dispatch(saveProduct(item))}
                    >
                      <Link
                        href={`/${locale}/products/${(item?.name)
                          .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                          .replace(/^-+|-+$/g, "")
                          .toLowerCase()}?id=${item.id}`}
                        locale={false}
                        className="absolute w-full  h-full top-0 left-0 z-[40] "
                      ></Link>
                      <p>{item?.name}</p>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div
            className={`hover:text-primary hover:bg-white border-[1px] border-solid border-primary  flex items-center justify-center mt-[100px] w-[100px] sm:w-[150px] py-1 px-2 cursor-pointer rounded-[10px] bg-primary text-white rotate-0 `}
            onClick={() => {
              // router.back();
              // window.scrollTo(0, 0);
              setDamagedProductsModalOpen(false);
              setCartParts("products");
              setIsValidRoute(false);
            }}
          >
            <FaArrowRightLong
              className={`text-[18px] lg:text-[20px] mx-2 ${
                locale === "en" ? "rotate-180" : ""
              }`}
            />
            <span className="inline-block me-2 text-[16px] font-semibold">
              {t("back")}
            </span>
          </div>
        </div>
      </Modal>
    </>
  );
}
