"use client";
import CardCart from "@comp/Cards/CardCart/page";
import NavBarDownCart from "@comp/Carts/component/NavBarDownCart/page";
import Navbar from "@comp/Navbar/page";
import AppContext from "@ctx/AppContext";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Chapar from "plugins/Chapar";
import PersianNumber from "plugins/PersianNumber";
import React, { useContext, useEffect } from "react";
import { toast } from "react-toastify";

const page = () => {
  const CTX = useContext(AppContext);
  const router = useRouter();
  const cart = CTX.state.cart;

  const calculateTotalCost = cart.reduce(
    (total, item) => total + parseInt(item.cost) * item.count,
    0
  );

  const calculateTotalCostWithDiscount = cart.reduce(
    (total, item) => total + parseInt(item.costWithDiscount) * item.count,
    0
  );

  // const calculateTotalCostWithDiscount = cart.reduce((total, item) => {
  //   // Check if costWithDiscount is defined and a valid number
  //   if (
  //     typeof item.costWithDiscount === "number" &&
  //     !isNaN(item.costWithDiscount)
  //   ) {
  //     // If costWithDiscount is defined and valid, include it in the calculation
  //     return total + item.costWithDiscount * item.count;
  //   } else {
  //     // If costWithDiscount is not defined or not a valid number, use regular cost
  //     return total + item.cost * item.count;
  //   }
  // }, 0);

  const handleGoCheckOut = async () => {
    // Check if the user is authorized based on the presence of a token in local storage
    const token = localStorage.getItem("token");

    if (token) {
      // If token exists, proceed to checkout
      const productsToSend = cart.map((item) => ({
        productId: item.id,
        count: parseInt(item.count),
      }));
      try {
        const data = await Chapar.post(
          `${process.env.NEXT_PUBLIC_API_URL}/order/bag/add`,

          JSON.stringify(productsToSend),

          {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          }
        );

        CTX.setCheckOutData(data);
      } catch ({ error, status }) {
        toast.error(`${error?.response?.data?.message}`, {
          position: "bottom-right",
          closeOnClick: true,
        });
      }
      router.push("/cart/checkout"); // Redirect to the checkout page
    } else {
      // If token does not exist, redirect to login
      router.push("/login"); // Redirect to the login page
    }
  };

  useEffect(() => {
    CTX.setBottomSheetCartOpen(false);
  }, []);

  return (
    <>
      <div className=" pb-20">
        <Navbar theme={1} />

        <div className="text-right flex rtl justify-between border-t-[1px] border-gray-200 my-3 px-4 ">
          <p className="mb-0 text-sm font-semibold py-4">محصولات انتخاب شده</p>

          <div className="bg-primary-200 w-fit h-fit relative my-3 p-1 rounded-lg">
            <p className="mb-0 text-[11px] text-white rtl">
              <PersianNumber number={cart?.length} style={"mx-1"} />
              محصول
            </p>
          </div>
        </div>

        <div className="">
          {cart?.map((e) => (
            <CardCart data={e} />
          ))}

          <div className="">
            <div className="text-right flex rtl justify-between border-y-[1px] border-gray-200 my-3 px-4 ">
              <p className="mb-0 text-sm font-semibold py-4">حساب نهایی</p>

              {/* <div className="bg-primary-200 w-fit h-fit relative my-3 p-1 rounded-lg">
                <p className="mb-0 text-[11px] text-white rtl">
                  <PersianNumber number={cart?.length} style={"mx-1"} />
                  محصول
                </p>
              </div> */}
            </div>

            <div>
              <div className="flex justify-between rtl px-4">
                <p className="mb-0 text-[12px] text-gray-500">قیمت </p>

                <div className="flex justify-center">
                  <p className="mb-0 ">
                    <PersianNumber
                      number={(calculateTotalCost / 10)?.toLocaleString()}
                      style={"!text-[14px] !font-semibold"}
                    />
                  </p>
                  <small className="text-gray-500 text-[12px] mt-1 mx-1">
                    {" "}
                    تومان
                  </small>
                </div>
              </div>

              <div className="flex justify-between rtl my-2 px-4">
                <p className="mb-0 text-[12px] text-gray-500">تخفیف محصول</p>

                <div className="flex justify-center">
                  <p className="mb-0 ">
                    <PersianNumber
                      number={(
                        (calculateTotalCost - calculateTotalCostWithDiscount) /
                        10
                      )?.toLocaleString()}
                      style={"!text-[14px] !font-semibold"}
                    />
                  </p>
                  <small className="text-gray-500 text-[12px] mt-1 mx-1">
                    {" "}
                    تومان
                  </small>
                </div>
              </div>

              <div className="flex justify-between bg-primary-100 p-3 rtl my-2">
                <p className="mb-0 text-sm text-primary-600 font-bold">
                  قابل پرداخت
                </p>

                <div className="flex justify-center">
                  <p className="mb-0 ">
                    <PersianNumber
                      number={
                        calculateTotalCostWithDiscount !== 0
                          ? (
                              calculateTotalCostWithDiscount / 10
                            )?.toLocaleString()
                          : 0
                      }
                      style={"!text-[14px] !font-semibold text-primary-800"}
                    />
                  </p>
                  <small className="text-gray-500 text-[12px] mt-1 mx-1">
                    {" "}
                    تومان
                  </small>
                </div>
              </div>
            </div>
          </div>
        </div>

        <NavBarDownCart
          calculateTotalCost={calculateTotalCostWithDiscount / 10}
          event={() => handleGoCheckOut()}
        />
      </div>
    </>
  );
};

export default page;
