import React, { useEffect, useState } from "react";
import ProductDefaultImage from "../../../assets/icons/photo.svg";
import GiftImage from "../../../assets/icons/presents.svg";
import { formatNumber } from "../../../utils";
import { useAppStore } from "../../../store/appStore";
import { useCartStore } from "../../../store/cartStore";
import { alerts } from "../../../utils/alerts";
import ModalDistributesProduct from "./ModalDistributesProduct";
import { InputNumber } from "antd";
import { IconArrowDown, IconTrash } from "../../../components/Icon";

type CartProductItemProps = {
  item: {
    id: number;
    quantity: number;
    item_price: number;
    is_bonus: boolean;
    before_discount_price: number;
    bonus_product_name: string;
    product: {
      id: number;
      name: string;
      price: number;
      check_inventory: boolean;
      quantity_in_stock_with_distribute: number;
      images: {
        image_url: any;
      }[];
      distributes: {
        element_distributes: {
          name: string;
          quantity_in_stock: number;
          sub_element_distributes: {
            quantity_in_stock: number;
            name: string;
          }[];
        }[];
      }[];
      product_discount: {
        discount_price: number;
        value: number;
      };
    };
    distributes_selected: {
      name: string;
      value: string;
      sub_element_distributes: string | null;
    }[];
  };
  endItem: boolean;
  isUseDiscountPrice: {
    is_use_points: boolean;
    is_use_balance_collaborator: boolean;
    is_use_balance_agency: boolean;
  };
  getAddressDefault: Function;
};

const CartProductItem = ({
  item,
  endItem,
  getAddressDefault,
}: CartProductItemProps) => {
  const {
    product,
    item_price,
    is_bonus,
    before_discount_price,
    distributes_selected,
    bonus_product_name,
  } = item;
  let {
    price,
    product_discount,
    distributes,
    quantity_in_stock_with_distribute,
    check_inventory,
  } = product;

  const { changeQuantityInCart } = useCartStore((state) => ({
    changeQuantityInCart: state.changeQuantityInCart,
  }));

  const [quantity, setQuantity] = useState(1);
  const [isShowDrawer, setShowDrawer] = useState(false);
  const { appTheme } = useAppStore((state) => state);
  let pastPrice = price;

  if (product_discount) price = product_discount.discount_price;

  //Handle Change Quantity
  const getMaxQuantity = (ele?: string, sub?: any) => {
    if (distributes == null || distributes.length == 0) {
      return quantity_in_stock_with_distribute;
    }

    if (sub != null) {
      for (const eleItem of distributes[0].element_distributes) {
        if (eleItem.name == ele) {
          for (const su of eleItem.sub_element_distributes) {
            if (su.name == sub) {
              return su.quantity_in_stock;
            }
          }
        }
      }
    }

    if (ele != null) {
      for (const eleItem of distributes[0].element_distributes) {
        if (eleItem.name == ele) {
          return eleItem.quantity_in_stock;
        }
      }
    }
    return quantity_in_stock_with_distribute;
  };

  const onIncrease = () => {
    var maxQuantity = getMaxQuantity();

    if (distributes_selected !== null) {
      maxQuantity = getMaxQuantity(
        distributes_selected[0]?.value,
        distributes_selected[0]?.sub_element_distributes
      );
    }

    if (
      maxQuantity == -1 ||
      quantity + 1 <= maxQuantity ||
      check_inventory === false
    ) {
      handleChangeBtnQuantity({
        line_item_id: item.id,
        product_id: product.id,
        quantity: quantity + 1,
        distributes: distributes_selected,
        code_voucher: "",
      });
      setQuantity(quantity + 1);
    } else {
      alerts.error("Đã vượt quá số lượng trong kho!");
    }
  };

  const onReduce = () => {
    if (quantity - 1 >= 1) {
      handleChangeBtnQuantity({
        line_item_id: item.id,
        product_id: product.id,
        quantity: quantity - 1,
        distributes: distributes_selected,
        code_voucher: "",
      });
      setQuantity(quantity - 1);
    }
  };

  const onRemove = () => {
    handleChangeBtnQuantity({
      line_item_id: item.id,
      product_id: product.id,
      quantity: 0,
      distributes: distributes_selected,
      code_voucher: "",
    });
    setQuantity(0);
  };

  const handleChangeBtnQuantity = (product, onSuccess = () => {}) => {
    const defaultAddress = getAddressDefault();
    changeQuantityInCart(
      product,
      defaultAddress.length > 0 ? defaultAddress[0] : {},
      onSuccess
    );
  };

  useEffect(() => {
    if (item.quantity) {
      setQuantity(item.quantity);
    }
  }, [item.quantity]);

  const image_url = product?.images[0]?.image_url
    ? product?.images[0]?.image_url
    : ProductDefaultImage;
  return is_bonus ? (
    <div
      className={`flex gap-[20px] py-[10px] mx-[20px] ${
        endItem ? "" : "border-b-[1px] border-[#e4e4e4]"
      } pl-[20px]`}
    >
      <div className="w-[50px] h-[50px] flex-shrink-0">
        <img
          className="w-full h-full object-cover"
          src={image_url}
          alt={product.name}
        />
      </div>
      <div className="flex w-full justify-between gap-x-2">
        <div className="flex justify-center flex-col">
          <div className="line-clamp-2">{product.name}</div>
          {distributes_selected?.length > 0 && (
            <div className="text-[10px] text-gray-500">
              Phân loại: {distributes_selected[0].value}{" "}
              {distributes_selected[0].sub_element_distributes}
            </div>
          )}
        </div>
        <div className="flex items-center gap-x-2 flex-shrink-0">
          <div className="text-red-500">x {item.quantity}</div>
          <div className="flex flex-col items-center gap-y-1">
            <div>
              <img src={GiftImage} alt="gift" className="w-5 h-5" />
            </div>
            <div className="text-[10px] line-clamp-2 w-12 text-center leading-3">
              {bonus_product_name}
            </div>
          </div>
        </div>
      </div>
    </div>
  ) : (
    <div
      className={`flex gap-x-[20px] py-[10px] mx-[20px] ${
        endItem ? "" : "border-b-[1px] border-[#e4e4e4]"
      }`}
    >
      <div className="w-[70px] h-[70px] relative flex-shrink-0">
        <img
          className="w-full h-full rounded-[4px] mt-0 object-cover"
          src={image_url}
          alt={product.name}
          loading="lazy"
        />
        {product_discount ? (
          <div className="absolute top-1 -left-[6px]">
            <svg
              width="45"
              height="22"
              viewBox="0 0 40 22"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              className="text-yellow-300"
            >
              <path
                d="M17.6883 15H0V1.72609C0 0.772741 0.341214 0 0.762179 0H17.6883C19.5174 0 21 3.35773 21 7.5C21 11.6423 19.5174 15 17.6883 15Z"
                fill="currentColor"
              />
              <path
                d="M0 14.5115V18.1291L4.61057 15.2574L0 14.5115Z"
                fill="currentColor"
              />
              <path
                d="M4.61076 15.2581C2.08805 15.2581 0.0424805 16.5437 0.0424805 18.1298C0.0424805 19.7159 2.08805 21.0015 4.61076 21.0015V15.2581Z"
                fill="#d2c400"
              />
              <path
                d="M40 15L2 15L2 0L40 0L34.6207 7.09677L40 15Z"
                fill="currentColor"
              />
            </svg>
            <div className="absolute text-[10px] text-red-400 -top-[2px] font-semibold left-2">
              -{product_discount.value}%
            </div>
          </div>
        ) : null}
      </div>

      <div className="flex flex-col justify-between gap-y-2 flex-1">
        <p className="line-clamp-2">{product.name}</p>
        {distributes_selected?.length > 0 && (
          <div className="text-[10px] text-gray-500">
            <div
              className="bg-[#e0e0e0] px-2 inline-flex items-center gap-x-1 active:bg-[#d6d6d6]"
              onClick={() => setShowDrawer(true)}
            >
              <span>
                Phân loại: {distributes_selected[0].value}{" "}
                {distributes_selected[0].sub_element_distributes}
              </span>
              <IconArrowDown className={"w-2 h-2"} />
            </div>
          </div>
        )}
        <div className="flex items-center gap-x-3">
          <div
            className="font-semibold"
            style={{
              color: appTheme.color_main_1,
            }}
          >
            {item_price > 0 ? `đ${formatNumber(item_price)}` : "Liên hệ"}
          </div>
          {pastPrice !== price && before_discount_price > 0 && (
            <div className="line-through text-xs text-slate-400">
              đ{formatNumber(before_discount_price)}
            </div>
          )}
        </div>

        <div>
          <div className="flex w-[100px]">
            <button
              className={`text-sm border border-[#d9d9d9] px-[11px] rounded-l-md text-center border-r-0 ${
                quantity !== 1
                  ? "bg-[rgba(0,0,0,0.01)]"
                  : "bg-[rgba(0,0,0,0.04)] text-[rgba(0,0,0,0.25)]"
              }`}
              disabled={quantity !== 1 ? false : true}
              onClick={onReduce}
            >
              -
            </button>

            <InputNumber
              className="rounded-none text-center w-full inputNumber h-full bg-[rgba(0,0,0,0.01)]"
              size="small"
              value={quantity}
              onClick={() => setShowDrawer(true)}
            />
            <button
              className={`text-sm border border-[#d9d9d9] px-[11px] rounded-r-md text-center bg-[rgba(0,0,0,0.01)] border-l-0`}
              onClick={onIncrease}
            >
              +
            </button>
            {isShowDrawer && (
              <ModalDistributesProduct
                item={item}
                image_url={image_url}
                isShowDrawer={isShowDrawer}
                setShowDrawer={setShowDrawer}
                getMaxQuantity={getMaxQuantity}
                handleChangeBtnQuantity={handleChangeBtnQuantity}
              ></ModalDistributesProduct>
            )}
          </div>
        </div>
      </div>
      <div className="flex items-center">
        <IconTrash className="w-5 h-5 text-red-500" onClick={onRemove} />
      </div>
    </div>
  );
};
export default CartProductItem;
