import React, { useEffect, useState } from "react";
import "./Cart_Products_card.css";
import { Table } from "react-bootstrap";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faShoppingBag, faTrashCan } from "@fortawesome/free-solid-svg-icons";

import Increment_decrement_btn_holder_add from "../../common-components/common_btn/increment_decrement_btn_holder/Increment_decrement_btn_holder_add";
import { deleteAllCart, getAllCart } from "../../../features/cart/cartSlice";
import { useDispatch, useSelector } from "react-redux";
import { encodeId, variant_type } from "../../../utils/common";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Order_summery_holder from "../may_you_like_also/order_summery_holder/Order_summery_holder";
import Green_btn from "../../common-components/common_btn/green_btn/Green_btn";

function Cart_Products_card({ data, instock, setInstock }) {
  const isSignin = useSelector((state) => state.auth.is_signin);
  const [error, setError] = useState("");
  const dispatch = useDispatch();
  const deleteCart = async (id, product_id, varient_id) => {
    const res = await dispatch(
      deleteAllCart({ id, isSignin, product_id, varient_id }),
    );
    if (res.meta?.requestStatus === "fulfilled") {
      await dispatch(getAllCart(isSignin));
    } else if (res.meta?.requestStatus === "rejected") {
      console.log("Error:", res.payload || "Not In Cart");
    }
  };
  const navigate = useRouter();
  useEffect(() => {
    if (data?.data?.length > 0) {
      const anyOutOfStock = data.data.some((val) => {
        const stock = Number(val?.Product_Variant?.general_stock);
        const quantity = Number(val?.quantity);
        return stock < quantity;
      });

      setInstock(anyOutOfStock);
    }
  }, [data]);

  const currentCurrency = useSelector((state) => state.master.currentCurrency);
  const rate = Number(currentCurrency?.rate) || 1;
  const symbol = currentCurrency?.symbol || "₹";

  console.log(data?.data, " without login ++ ++ ");

  const hasCartItems = data?.data && data.data.length > 0;

  return (
    <>
      <section className="Cart_Products_card">
        <div className="container">
          {hasCartItems ? (
            <div className="row justify-content-center">
              <div className="col-lg-8">
                <div className="ContinueShopping_text">
                  <Link href={"/shop"}>
                    <p>Continue Shopping</p>
                  </Link>
                </div>

                <div className="desktop_viw_table_holder">
                  <div className="table-responsive">
                    <Table>
                      <thead>
                        <tr>
                          <th></th>
                          <th className="text-end">
                            <b>Total</b>
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {data?.data?.map((val) => {
                          let stock;
                          if (
                            Number(val?.Product?.variant_type_id) ===
                            Number(variant_type.Single)
                          ) {
                            stock = Number(val?.Product_Variant?.general_stock);
                          } else if (
                            Number(val?.Product?.variant_type_id) ===
                            Number(variant_type.Double)
                          ) {
                            stock = Number(val?.Double_Variant?.stock);
                          } else if (
                            Number(val?.Product?.variant_type_id) ===
                            Number(variant_type.Triple)
                          ) {
                            stock = Number(val?.Triple_Variant?.stock);
                          }
                          const isInstock = stock <= val?.quantity;

                          const isInstockerror = stock < val?.quantity;
                          setInstock(isInstockerror);
                          const quantity = Number(val?.quantity);

                          const mrp = Number(
                            val.Triple_Variant?.mrp ||
                              val.Double_Variant?.mrp ||
                              val.Product_Variant?.mrp,
                          );

                          const price = Number(
                            val.Triple_Variant?.price ||
                              val.Double_Variant?.price ||
                              val.Product_Variant?.price,
                          );

                          const finalmrp = Number(mrp * rate).toFixed(2);
                          const finalprice = Number(price * rate).toFixed(2);
                          // contst
                          return (
                            <tr
                              key={
                                val.id ?? `${val.product_id}-${val.variant_id}`
                              }
                            >
                              <td>
                                <div className="product_holder">
                                  <div
                                    className="left_div"
                                    onClick={() =>
                                      navigate.push(
                                        `/product-details/${encodeId(
                                          val.product_id,
                                        )}`,
                                      )
                                    }
                                    style={{ cursor: "pointer" }}
                                  >
                                    <div className="img_holder">
                                      <img
                                        className="Product_img"
                                        src={`${process.env.NEXT_PUBLIC_IMG_URL}${val.Product?.image}`}
                                        alt={
                                          val.Product?.name || "Product image"
                                        }
                                      />
                                    </div>
                                  </div>

                                  <div className="right_div">
                                    <div className="info_text_holder">
                                      <div>
                                        <h4>{val.Product?.name}</h4>
                                        <p className="price_text">
                                          {"   "}
                                          {symbol} {finalprice}
                                          <span>
                                            {symbol} {finalmrp}
                                          </span>
                                        </p>
                                        <h6 className="weight_text">
                                          {val?.Product?.variant_type_id ===
                                            variant_type.Single && (
                                            <>
                                              <strong>
                                                {val?.Product?.variant_name} :
                                              </strong>{" "}
                                              {
                                                val?.Product_Variant?.Metal
                                                  ?.name
                                              }
                                            </>
                                          )}

                                          {val?.Product?.variant_type_id ===
                                            variant_type.Double && (
                                            <>
                                              <strong>
                                                {val?.Product?.variant_name} :
                                              </strong>{" "}
                                              {
                                                val?.Double_Variant
                                                  ?.Product_Variant?.Metal?.name
                                              }
                                              <br></br>
                                              <strong>Size:</strong>{" "}
                                              {
                                                val?.Double_Variant?.Size?.name
                                              }{" "}
                                            </>
                                          )}

                                          {val?.Product?.variant_type_id ===
                                            variant_type.Triple && (
                                            <>
                                              {/* <strong>Variant :</strong>{" "}
                                          {
                                            val?.Triple_Variant?.Double_Variant
                                              ?.Product_Variant?.Metal?.name
                                          }
                                          ,  */}
                                              <strong>Size:</strong>{" "}
                                              {
                                                val?.Triple_Variant
                                                  ?.Double_Variant?.Size?.name
                                              }
                                              , <strong>Diamond:</strong>{" "}
                                              {
                                                val?.Triple_Variant?.Diamond
                                                  ?.name
                                              }
                                            </>
                                          )}
                                        </h6>
                                        {instock && isInstockerror && (
                                          <p className="text-danger mt-2">
                                            Out of stock (Available: {stock})
                                          </p>
                                        )}
                                      </div>
                                    </div>
                                    <div className="Quantity_tr_holder ">
                                      <Increment_decrement_btn_holder_add
                                        val={val}
                                        quantity={val.quantity}
                                        setInstock={setInstock}
                                        setError={setError}
                                        error={error}
                                        isInstock={isInstock}
                                      />
                                      <div className="delete_icon_div">
                                        <FontAwesomeIcon
                                          className="trash_icon"
                                          icon={faTrashCan}
                                          onClick={() =>
                                            deleteCart(
                                              val.id,
                                              val.product_id,
                                              val.variant_id,
                                            )
                                          }
                                        />
                                      </div>
                                    </div>
                                    {isInstock && error && (
                                      <p
                                        className="error_text"
                                        style={{ color: "red" }}
                                      >{`Only ${stock} quantity in stock`}</p>
                                    )}
                                  </div>
                                </div>
                              </td>

                              <td>
                                <div className="price_holder">
                                  <p className="price_text">
                                    {/* <span>
                                      {symbol}{" "}
                                      {Number(
                                        finalmrp * Number(val.quantity),
                                      ).toFixed(2)}
                                    </span> */}
                                    {"   "}
                                    {symbol}{" "}
                                    {Number(
                                      finalprice * Number(val.quantity),
                                    ).toFixed(2)}{" "}
                                  </p>
                                </div>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </Table>
                  </div>
                </div>

                <div className="mobile_view_table_holder">
                  {data?.data?.map((val, index) => {
                    // ✅ get mrp & price for each item
                    const mrp = Number(
                      val?.Product_Variant?.mrp ||
                        val?.Double_Variant?.mrp ||
                        val?.Triple_Variant?.mrp ||
                        0,
                    );

                    const price = Number(
                      val?.Product_Variant?.price ||
                        val?.Double_Variant?.price ||
                        val?.Triple_Variant?.price ||
                        0,
                    );

                    // ✅ convert with currency rate
                    const finalmrp = `${symbol} ${(mrp * rate).toFixed(2)}`;
                    const finalprice = `${symbol} ${(price * rate).toFixed(2)}`;
                    let stock;
                    if (
                      Number(val?.Product?.variant_type_id) ===
                      Number(variant_type.Single)
                    ) {
                      stock = Number(val?.Product_Variant?.general_stock);
                    } else if (
                      Number(val?.Product?.variant_type_id) ===
                      Number(variant_type.Double)
                    ) {
                      stock = Number(val?.Double_Variant?.stock);
                    } else if (
                      Number(val?.Product?.variant_type_id) ===
                      Number(variant_type.Triple)
                    ) {
                      stock = Number(val?.Triple_Variant?.stock);
                    }
                    const isInstock = stock <= val?.quantity;
                    const isInstockerror = stock < val?.quantity;
                    const quantity = Number(val?.quantity);

                    return (
                      <div className="mobile_product_card" key={index}>
                        <div className="product_holder">
                          <div className="left_div">
                            <div className="img_holder">
                              <img
                                src={
                                  process.env.NEXT_PUBLIC_IMG_URL +
                                  val?.Product?.image
                                }
                                className="prod_img"
                                alt="product"
                              />
                            </div>
                          </div>

                          <div className="right_div">
                            <div className="descn_holder">
                              <div>
                                <h4 className="product_name mb-2">
                                  {val.Product?.name}
                                </h4>
                                <p className="price_text">
                                  {finalprice}
                                  <span>{finalmrp}</span>
                                </p>
                                <h6 className="new-varint">
                                  {val?.Product?.variant_type_id ===
                                    variant_type.Single && (
                                    <>
                                      {/* <strong>Variant :</strong>{" "} */}
                                      <strong>
                                        {" "}
                                        {val?.Product?.variant_name} :
                                      </strong>{" "}
                                      {val?.Product_Variant?.Metal?.name}
                                    </>
                                  )}

                                  {val?.Product?.variant_type_id ===
                                    variant_type.Double && (
                                    <>
                                      <strong>
                                        {val?.Product?.variant_name} :
                                      </strong>{" "}
                                      {
                                        val?.Double_Variant?.Product_Variant
                                          ?.Metal?.name
                                      }
                                      <br></br>
                                      <strong>Size:</strong>{" "}
                                      {val?.Double_Variant?.Size?.name}{" "}
                                    </>
                                  )}

                                  {val?.Product?.variant_type_id ===
                                    variant_type.Triple && (
                                    <>
                                      {/* <strong>Variant :</strong>{" "}
                                          {
                                            val?.Triple_Variant?.Double_Variant
                                              ?.Product_Variant?.Metal?.name
                                          }
                                          ,  */}
                                      <strong>Size:</strong>{" "}
                                      {
                                        val?.Triple_Variant?.Double_Variant
                                          ?.Size?.name
                                      }
                                      , <strong>Diamond:</strong>{" "}
                                      {val?.Triple_Variant?.Diamond?.name}
                                    </>
                                  )}
                                  {/* Variant :{" "}
                                      <span>
                                        {val?.Product_Variant?.Metal?.name ||
                                          val?.Double_Variant?.Product_Variant
                                            ?.Metal?.name ||
                                          val?.Triple_Variant?.Double_Variant
                                            ?.Product_Variant?.Metal?.name}
                                      </span> */}
                                </h6>
                                {instock && isInstockerror && (
                                  <p className="text-danger mt-2">
                                    Out of stock (Available: {stock})
                                  </p>
                                )}
                              </div>

                              <div className="all_btns_holder">
                                <div className="Quantity_tr_holder">
                                  <Increment_decrement_btn_holder_add
                                    val={val}
                                    quantity={val.quantity}
                                    setInstock={setInstock}
                                    setError={setError}
                                    error={error}
                                    isInstock={isInstock}
                                  />

                                  <div className="delete_icon_div">
                                    <FontAwesomeIcon
                                      className="trash_icon"
                                      icon={faTrashCan}
                                      onClick={() =>
                                        deleteCart(
                                          val.id,
                                          val.product_id,
                                          val.variant_id,
                                        )
                                      }
                                    />
                                  </div>
                                </div>
                                {isInstock && error && (
                                  <p
                                    className="error_text"
                                    style={{ color: "red" }}
                                  >{`Only ${stock} quantity in stock`}</p>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="col-lg-4 col-md-8">
                <Order_summery_holder instock={instock} data={data} />
              </div>
            </div>
          ) : (
            /* sober Empty Cart UI */
            <div className="empty-cart-container">
              <div className="empty-cart-icon-box">
                <FontAwesomeIcon icon={faShoppingBag} />
              </div>
              <h3 className="empty-cart-title">Your Cart is Empty</h3>
              <p className="empty-cart-description">
                Looks like you haven't added any items to your shopping cart
                yet.
              </p>
              <Green_btn
                btnText={"Start Shopping"}
                onClick={() => navigate.push("/shop")}
              />
            </div>
          )}
        </div>
      </section>
    </>
  );
}

export default Cart_Products_card;
