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

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { 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";

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 || "₹";
  return (
    <>
      <section className="Cart_Products_card">
        <div className="container">
          <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>Product</th>
                    <th className="text-center">Quantity</th>
                    <th className="text-end">
                      <b>Total</b>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {data?.data?.length > 0 ? (
                    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);

                      return (
                        <tr
                          key={val.id ?? `${val.product_id}-${val.variant_id}`}
                        >
                          <td>
                            <div className="row">
                              <div
                                className="col-md-4 col-12"
                                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="col-md-8 col-12">
                                <div className="info_text_holder">
                                  <div>
                                    <h4>{val.Product?.name}</h4>
                                    <p className="price_text">
                                      <span>
                                        {symbol} {finalmrp}
                                      </span>
                                      {symbol} {finalprice}
                                    </p>
                                    <h6>
                                      {val?.Product?.variant_type_id ===
                                        variant_type.Single && (
                                        <>
                                          <strong>Variant :</strong>{" "}
                                          {val?.Product_Variant?.Metal?.name}
                                        </>
                                      )}

                                      {val?.Product?.variant_type_id ===
                                        variant_type.Double && (
                                        <>
                                          {/* <strong>Variant :</strong>{" "}
                                          {
                                            val?.Double_Variant?.Product_Variant
                                              ?.Metal?.name
                                          } */}
                                          <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>
                              </div>
                            </div>
                          </td>

                          <td>
                            <div className="Quantity_tr_holder justify-content-center">
                              <Increment_decrement_btn_holder_add
                                val={val}
                                quantity={val.quantity}
                                setInstock={setInstock}
                                setError={setError}
                                error={error}
                                isInstock={isInstock}
                              />
                              <FontAwesomeIcon
                                className="trash_icon"
                                icon={faTrashCan}
                                onClick={() =>
                                  deleteCart(
                                    val.id,
                                    val.product_id,
                                    val.variant_id,
                                  )
                                }
                              />
                            </div>
                            {isInstock && error && (
                              <p
                                style={{ color: "red" }}
                              >{`Only ${stock} quantity in stock`}</p>
                            )}
                          </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>
                      );
                    })
                  ) : (
                    <tr>
                      <td colSpan={3} className="text-center">
                        No Data Available
                      </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="row">
                    <div className="col-5">
                      <div className="img_holder">
                        <img
                          src={
                            process.env.NEXT_PUBLIC_IMG_URL +
                            val?.Product?.image
                          }
                          className="prod_img"
                          alt="product"
                        />
                      </div>
                    </div>

                    <div className="col-7">
                      <div className="descn_holder">
                        <p className="product_name">{val?.Product?.name}</p>

                        {/* ✅ price display */}
                        <p className="price_text">
                          {finalprice}
                          <span className="mrp_text">{finalmrp}</span>
                        </p>

                        <p className="weight_text">
                          Size:
                          <span>
                            {val?.Product_Variant?.Metal?.name ||
                              val?.Double_Variant?.Product_Variant?.Metal
                                ?.name ||
                              val?.Triple_Variant?.Double_Variant
                                ?.Product_Variant?.Metal?.name}
                          </span>
                        </p>

                        <div className="all_btns_holder">
                          <div className="Quantity_tr_holder">
                            <Increment_decrement_btn_holder_add
                              val={val}
                              quantity={val?.quantity}
                            />

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

export default Cart_Products_card;
