import { Button as ButtonAnt, Drawer, InputNumber } from "antd";
import React, { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { IconCheck, IconClose } from "../../../components/Icon";
import Button from "../../../components/common/Button";
import { useAppStore } from "../../../store/appStore";
import { useCartStore } from "../../../store/cartStore";
import { formatPriceOrContact } from "../../../utils";
import { alerts } from "../../../utils/alerts";
import { findStock } from "../../../utils/productUltis";
import { useUserStore } from "../../../store/userStore";
type CartProductItemModalProps = {
  product: {
    id: number;
    name: string;
    price: number;
    check_inventory: boolean;
    min_price: number;
    max_price: number;
    min_price_before_override: number;
    max_price_before_override: number;
    quantity_in_stock_with_distribute: number;
    distributes: {
      name: string;
      sub_element_distribute_name: string;
      element_distributes: {
        id: number;
        name: string;
        price: number;
        image_url: string;
        quantity_in_stock: number;
        sub_element_distributes: {
          id: number;
          name: string;
          price: number;
          quantity_in_stock: number;
        }[];
      }[];
    }[];
    product_discount: {
      discount_price: number;
      value: number;
    };
  };
  isShowDrawer: boolean;
  setShowDrawer: Function;
  typeAddToCart: string;
  setTypeAddToCart: Function;
  image_url?: string;
  onSuccess: Function;
};
export default function ModalDistributesProduct({
  isShowDrawer,
  setShowDrawer,
  typeAddToCart,
  setTypeAddToCart,
  image_url,
  product,
}: CartProductItemModalProps) {
  let {
    price,
    product_discount,
    distributes,
    check_inventory,
    quantity_in_stock_with_distribute,
    min_price,
    max_price,
    min_price_before_override,
    max_price_before_override,
  } = product;
  let pastPrice = price;
  if (product_discount) price = product_discount.discount_price;

  const navigate = useNavigate();
  const { appTheme } = useAppStore((state) => state);
  const { addCart, loadingAddToCart } = useCartStore((state) => state);
  const [quantity, setQuantity] = useState(1);
  const [selectedProduct, setSelectedProduct] = useState({
    value: "",
    sub_element_distributes: "",
    price: 0,
    quantityInStock:
      quantity_in_stock_with_distribute > 0 || check_inventory == false
        ? 1
        : quantity_in_stock_with_distribute === -1
        ? 1
        : 0,
  });

  const quantityInputRef = useRef();
  const [selectedFilter, setSelectedFilter] = useState({
    indexDistribute: -1,
    indexSubDistribute: -1,
    numberQuantity:
      quantity_in_stock_with_distribute > 0 || check_inventory == false
        ? 1
        : quantity_in_stock_with_distribute === -1
        ? 1
        : 0,
  });
  const { getUserBadges } = useUserStore((state) => state);

  const handleSelectedDistribute = (index: number) => {
    setQuantity(1);
    setSelectedFilter((prev) => ({ ...prev, indexDistribute: index }));
    let priceCurrent = 0;
    let quantityCurrent = 0;
    let value = "";

    if (selectedFilter.indexSubDistribute !== -1) {
      if (
        distributes[0].element_distributes[index].sub_element_distributes
          .length > 0
      ) {
        priceCurrent =
          distributes[0].element_distributes[index].sub_element_distributes[
            selectedFilter.indexSubDistribute
          ].price ?? min_price;
        quantityCurrent =
          distributes[0].element_distributes[index].sub_element_distributes[
            selectedFilter.indexSubDistribute
          ].quantity_in_stock ?? quantity_in_stock_with_distribute;
        value = distributes[0].element_distributes[index].name;
      } else {
        priceCurrent = min_price;
        quantityCurrent = quantity_in_stock_with_distribute;
        value = distributes[0].element_distributes[index].name;
      }

      setSelectedProduct((prev) => ({
        ...prev,
        value: value,
        price: priceCurrent,
        quantityInStock: quantityCurrent,
      }));
      return;
    }

    if (
      distributes[0].element_distributes[index].sub_element_distributes
        .length === 0
    ) {
      priceCurrent = distributes[0].element_distributes[index].price;
      quantityCurrent =
        distributes[0].element_distributes[index].quantity_in_stock;
      value = distributes[0].element_distributes[index].name;
      setSelectedProduct((prev) => ({
        ...prev,
        value: value,
        sub_element_distributes: "",
        price: priceCurrent ? priceCurrent : prev.price,
        quantityInStock: quantityCurrent,
      }));
    } else {
      value = distributes[0].element_distributes[index].name;
      setSelectedProduct((prev) => ({
        ...prev,
        value: value,
      }));
    }
  };

  const handleSelectSubdistribute = (index: number) => {
    setQuantity(1);
    setSelectedFilter((prev) => ({ ...prev, indexSubDistribute: index }));
    let priceCurrent = 0;
    let quantityCurrent = 0;
    let sub_element_distributes = "";

    if (selectedFilter.indexDistribute !== -1) {
      if (
        distributes[0].element_distributes[selectedFilter.indexDistribute]
          .sub_element_distributes.length > 0
      ) {
        priceCurrent =
          distributes[0].element_distributes[selectedFilter.indexDistribute]
            .sub_element_distributes[index].price;
        quantityCurrent =
          distributes[0].element_distributes[selectedFilter.indexDistribute]
            .sub_element_distributes[index].quantity_in_stock;
        sub_element_distributes =
          distributes[0].element_distributes[selectedFilter.indexDistribute]
            .sub_element_distributes[index].name;
      } else {
        priceCurrent = min_price;
        quantityCurrent = quantity_in_stock_with_distribute;
      }

      setSelectedProduct((prev) => ({
        ...prev,
        sub_element_distributes: sub_element_distributes,
        price: priceCurrent ? priceCurrent : prev.price,
        quantityInStock: quantityCurrent,
      }));
    }
  };

  const onIncrease = () => {
    if (
      selectedProduct.quantityInStock == -1 ||
      quantity + 1 <= selectedProduct.quantityInStock ||
      check_inventory === false
    ) {
      setQuantity(quantity + 1);
    } else {
      alerts.error("Đã vượt quá số lượng trong kho!");
    }
  };
  const onReduce = () => {
    if (quantity - 1 >= 1) {
      setQuantity(quantity - 1);
    }
  };

  const handleChangeQuatity = (value: any) => {
    if (
      selectedProduct.quantityInStock == -1 ||
      Number(value) <= selectedProduct.quantityInStock ||
      check_inventory === false
    ) {
      setQuantity(value);
    } else {
      if (quantityInputRef.current !== value) {
        alerts.error("Đã vượt quá số lượng trong kho!");
        quantityInputRef.current = value;
      }
    }
  };
  const handleChangeDistribute = () => {
    const token = localStorage.getItem("token");
    if (!token) {
      navigate("/request-login");
      return;
    }
    if (distributes.length && selectedFilter.indexDistribute === -1) {
      alerts.error(`Chưa chọn: ${distributes[0].name}!`);
      return;
    }
    if (
      distributes.length &&
      selectedFilter.indexSubDistribute === -1 &&
      distributes[0].sub_element_distribute_name
    ) {
      alerts.error(`Chưa chọn: ${distributes[0].sub_element_distribute_name}!`);
      return;
    }

    const data = {
      product_id: product.id,
      quantity,
      distributes: [
        distributes[0]?.name
          ? {
              name: distributes[0]?.name,
              value: selectedProduct.value,
              sub_element_distributes: selectedProduct.sub_element_distributes,
            }
          : {},
      ],
    };
    addCart(data, () => {
      setShowDrawer(false);
      alerts.success("Đã thêm vào giỏ hàng");
      if (typeAddToCart === "buyNow") {
        navigate("/cart");
        setTypeAddToCart("");
      }
      getUserBadges();
    });
  };

  return (
    <Drawer
      placement={"bottom"}
      open={isShowDrawer}
      onClose={() => setShowDrawer(false)}
      height={"h-[100vh]"}
      headerStyle={{ display: "none" }}
      bodyStyle={{ padding: 0 }}
    >
      <div className="flex gap-5 p-3 border-b-[1px] border-[#e4e4e4]">
        <img className="w-[70px] h-[70px]" src={image_url} alt={product.name} />
        <div className="flex flex-col justify-center">
          <div
            className="font-semibold text-base"
            style={{
              color: appTheme.color_main_1,
            }}
          >
            {selectedProduct.price > 0 ? (
              formatPriceOrContact(
                !product_discount?.value
                  ? selectedProduct.price
                  : selectedProduct.price -
                      selectedProduct.price * product_discount.value * 0.01
              )
            ) : (
              <>
                {min_price === max_price ? (
                  <div
                    className="price"
                    style={{ color: appTheme.color_main_1 }}
                  >
                    {formatPriceOrContact(
                      !product_discount?.value
                        ? min_price
                        : min_price - min_price * product_discount?.value * 0.01
                    )}
                  </div>
                ) : (
                  <div
                    className="price"
                    style={{ color: appTheme.color_main_1 }}
                  >
                    {formatPriceOrContact(
                      !product_discount?.value
                        ? min_price
                        : min_price - min_price * product_discount?.value * 0.01
                    )}
                    {" - "}

                    {formatPriceOrContact(
                      !product_discount?.value
                        ? max_price
                        : max_price - max_price * product_discount?.value * 0.01
                    )}
                  </div>
                )}
              </>
            )}
          </div>
          {product_discount?.value > 0 ? (
            <div className="flex gap-x-2">
              <div className="line-through text-xs text-slate-500">
                {selectedProduct.price > 0 ? (
                  formatPriceOrContact(selectedProduct.price)
                ) : (
                  <>
                    {min_price === max_price ? (
                      <div>{formatPriceOrContact(min_price)}</div>
                    ) : (
                      <div>
                        {formatPriceOrContact(min_price)}
                        {" - "}

                        {formatPriceOrContact(max_price)}
                      </div>
                    )}
                  </>
                )}
              </div>
              <div className="text-xs text-red-400 font-medium">
                -{product_discount?.value}%
              </div>
            </div>
          ) : null}
        </div>
      </div>
      {distributes?.length > 0 && (
        <div className="p-3 border-b-[1px] border-[#e4e4e4]">
          <div className="flex flex-col gap-y-2">
            {distributes.map((distribute) => (
              <div key={distribute.name}>
                <div className="font-semibold mb-1">{distribute.name}</div>
                <div className="flex gap-x-2">
                  {distribute.element_distributes?.length > 0 &&
                    distribute.element_distributes.map(
                      (elementDistribute, index) => (
                        <div
                          key={elementDistribute.id}
                          className="bg-[#e9e9e9] inline-block px-[10px] py-1 relative overflow-hidden"
                          onClick={() => handleSelectedDistribute(index)}
                        >
                          <span>{elementDistribute.name}</span>
                          {selectedFilter.indexDistribute === index ? (
                            <div
                              className="absolute top-0 left-0 w-8 h-8 -translate-y-6 -translate-x-[10px]  -rotate-[30deg]"
                              style={{
                                backgroundColor: appTheme.color_main_1,
                              }}
                            >
                              <IconCheck
                                className={
                                  "w-[9px] h-[9px] absolute bottom-[1px] left-[5px] text-[#fff] rotate-[30deg]"
                                }
                              />
                            </div>
                          ) : null}
                        </div>
                      )
                    )}
                </div>
              </div>
            ))}

            {distributes != null &&
              distributes.length > 0 &&
              distributes[0] &&
              distributes[0].sub_element_distribute_name != null &&
              distributes[0].sub_element_distribute_name && (
                <div>
                  <div className="font-semibold mb-1">
                    {distributes[0].sub_element_distribute_name}
                  </div>
                  <div className="flex gap-x-2">
                    {distributes[0].element_distributes[0]
                      ?.sub_element_distributes.length > 0 &&
                      distributes[0].element_distributes[0]?.sub_element_distributes.map(
                        (subElementDistribute, indexChild) => (
                          <div
                            key={subElementDistribute.id}
                            className="bg-[#e9e9e9] inline-block px-[10px] py-1 relative overflow-hidden"
                            onClick={() =>
                              handleSelectSubdistribute(indexChild)
                            }
                          >
                            <span>{subElementDistribute.name}</span>
                            {selectedFilter.indexSubDistribute ===
                            indexChild ? (
                              <div
                                className="absolute top-0 left-0 w-8 h-8 -translate-y-6 -translate-x-[10px]  -rotate-[30deg]"
                                style={{
                                  backgroundColor: appTheme.color_main_1,
                                }}
                              >
                                <IconCheck
                                  className={
                                    "w-[9px] h-[9px] absolute bottom-[1px] left-[5px] text-[#fff] rotate-[30deg]"
                                  }
                                />
                              </div>
                            ) : null}
                          </div>
                        )
                      )}
                  </div>
                </div>
              )}
          </div>
        </div>
      )}

      <div className="flex justify-between  items-center p-5">
        <p>Số lượng</p>
        <div className="w-[110px] flex">
          <button
            className={`text-sm border border-[#d9d9d9] px-[11px] rounded-l-md text-center border-r-0 ${
              (product.check_inventory == false ||
                findStock(
                  product,
                  selectedProduct.value,
                  selectedProduct.sub_element_distributes
                ) === -1 ||
                findStock(
                  product,
                  selectedProduct.value,
                  selectedProduct.sub_element_distributes
                ) > 0) &&
              quantity !== 1
                ? "bg-[rgba(0,0,0,0.02)]"
                : "bg-[rgba(0,0,0,0.04)] text-[rgba(0,0,0,0.25)]"
            }`}
            disabled={
              (product.check_inventory == false ||
                findStock(
                  product,
                  selectedProduct.value,
                  selectedProduct.sub_element_distributes
                ) === -1 ||
                findStock(
                  product,
                  selectedProduct.value,
                  selectedProduct.sub_element_distributes
                ) > 0) &&
              quantity !== 1
                ? false
                : true
            }
            onClick={onReduce}
          >
            -
          </button>
          <InputNumber
            className="rounded-none text-center w-full inputNumber"
            value={quantity}
            onChange={handleChangeQuatity}
            min={1}
            disabled={
              product.check_inventory == false ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) === -1 ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) > 0
                ? false
                : true
            }
          />
          <button
            className={`text-sm border border-[#d9d9d9] px-[11px] rounded-r-md text-center ${
              product.check_inventory == false ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) === -1 ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) > 0
                ? "bg-[rgba(0,0,0,0.02)]"
                : "bg-[rgba(0,0,0,0.04)] text-[rgba(0,0,0,0.25)]"
            } border-l-0`}
            disabled={
              product.check_inventory == false ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) === -1 ||
              findStock(
                product,
                selectedProduct.value,
                selectedProduct.sub_element_distributes
              ) > 0
                ? false
                : true
            }
            onClick={onIncrease}
          >
            +
          </button>
        </div>
      </div>
      {product.check_inventory == false ||
      findStock(
        product,
        selectedProduct.value,
        selectedProduct.sub_element_distributes
      ) === -1 ||
      findStock(
        product,
        selectedProduct.value,
        selectedProduct.sub_element_distributes
      ) > 0 ? (
        <>
          {loadingAddToCart ? (
            <ButtonAnt
              className="w-[90%] mx-auto flex items-center justify-center py-4"
              type="primary"
              style={{
                backgroundColor: appTheme.color_main_1,
              }}
              loading
            >
              {typeAddToCart === "buyNow" ? "Mua ngay" : "Thêm vào giỏ hàng"}
            </ButtonAnt>
          ) : (
            <Button
              className="w-[90%] mx-auto flex items-center justify-center py-4"
              type="primary"
              style={{
                backgroundColor: appTheme.color_main_1,
              }}
              onClick={handleChangeDistribute}
            >
              {typeAddToCart === "buyNow" ? "Mua ngay" : "Thêm vào giỏ hàng"}
            </Button>
          )}
        </>
      ) : (
        <Button
          className="w-[90%] mx-auto flex items-center justify-center py-4 bg-gray-300"
          isDefault
        >
          Hết hàng
        </Button>
      )}
      <button>
        <IconClose
          onClick={() => setShowDrawer(false)}
          className="absolute right-[10px] top-[10px] w-[24px] h-[24px]"
        />
      </button>
    </Drawer>
  );
}
