import { RiDeleteBin6Line } from 'react-icons/ri';
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { MdCurrencyRupee } from 'react-icons/md';
import horizontal from '../../../Images/defaultItemImg.png';
import '../../../Styles/Kiosk/OrderView/OrderView3.scss';
import KioskHeader from '../Components/KioskHeader';
import KioskFooter from '../Components/KioskFooter';
import KioskFooter2 from '../Components/KioskFooter2';
import {
  changeKioskPageName,
  getKioskLightColour,
} from '../../../Features/Kiosk/kiosk';
import {
  GlobalKioskOrderDetails,
  changeKioskOrderDetails,
} from '../../../Features/BookingScreen/BookingData/KioskBookingData';
import KioskFooter3 from '../Components/KioskFooter3';
import PozoDineInIcon from '../KioskIcons/KioskDineIn';
import TakeAway from '../KioskIcons/KioskTakeAway';
import { PreferenceData } from '../../../Features/BookingScreen/BookingData/BookingData';
import { calculateOverAllQtyLimit } from '../../../utils/calculations';
import { message } from 'antd';
import { IoIosWarning } from 'react-icons/io';

const KioskOrderView = (props) => {
  console.log(props, 'propsprops');
  const KioskThemeData = props?.hasOwnProperty('KioskThemeData')
    ? props['KioskThemeData']
    : null;
  const dispatch = useDispatch();
  const KioskOrderDetails = useSelector(GlobalKioskOrderDetails);
  const getKioskLightColourdata = useSelector(getKioskLightColour);
  const preferenceDatas = useSelector(PreferenceData);
  const [maxLimitExceeded, setMaxLimitExceeded] = useState(false);
  const overAllLimitPreferenece =
    preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
      (item) => (item.SettingIdName?.toLowerCase() === 'overalllimit') && item?.SettingValue === 'Y');
  const itemWiseLimitPreferenece =
    preferenceDatas?.[0]?.['SettingDtlDetails']?.find(
      (item) => item.SettingIdName?.toLowerCase() === 'itemwiselimit' && item?.SettingValue === 'Y');
  const maxQtyLimit = itemWiseLimitPreferenece?.SettingCount || overAllLimitPreferenece?.SettingCount || null;

  const BackToCategory = async () => {
    await dispatch(changeKioskPageName('categoryPage'));
  };
  const removeFromCart = async (item) => {
    await dispatch(
      changeKioskOrderDetails(
        KioskOrderDetails?.filter(
          (cartItem) =>
            !(
              cartItem?.ProdId === item?.ProdId &&
              cartItem?.InwardDtlId === item?.InwardDtlId &&
              cartItem?.OrderRate === item?.OrderRate &&
              cartItem?.BookingTypeName === item?.BookingTypeName
            )
        )
      )
    );
  };
  const increase = async (item) => {

    if ((overAllLimitPreferenece || itemWiseLimitPreferenece) && maxQtyLimit) {
      if (overAllLimitPreferenece) {
        const calculatedOverAllQty = calculateOverAllQtyLimit(KioskOrderDetails);
        if ((calculatedOverAllQty + 1) > maxQtyLimit) {
          setMaxLimitExceeded(true);
          // Reset after 3 seconds
          setTimeout(() => {
            setMaxLimitExceeded(false);
          }, 2000);
          return;
        }
      }
    }
    await dispatch(
      changeKioskOrderDetails(
        KioskOrderDetails?.map(
          (
            cartItem // if the item is already in the cart, increase the quantity of the item
          ) =>
            cartItem.ProdId === item.ProdId &&
              cartItem.InwardDtlId === item.InwardDtlId &&
              cartItem.OrderRate === item.OrderRate &&
              cartItem?.BookingTypeName === item?.BookingTypeName
              ? {
                ...cartItem,
                OrderQty: cartItem.OrderQty + 1,
                TotalAmt: (cartItem.OrderQty + 1) * cartItem.OrderRate,
                TaxAmt: (
                  ((cartItem.OrderQty + 1) *
                    cartItem.OrderRate *
                    cartItem.TaxPercentage) /
                  (100 + cartItem.TaxPercentage)
                ).toFixed(2),
                WithoutTaxRate:
                  (cartItem.OrderQty + 1) * cartItem.OrderRate -
                  (
                    ((cartItem.OrderQty + 1) *
                      cartItem.OrderRate *
                      cartItem.TaxPercentage) /
                    (100 + cartItem.TaxPercentage)
                  ).toFixed(2),
              }
              : cartItem // otherwise, return the cart item
        )
      )
    );
  };
  const decrease = async (item) => {
    const isItemInCart = KioskOrderDetails?.find(
      (cartItem) =>
        cartItem.ProdId === item.ProdId &&
        cartItem.InwardDtlId === item.InwardDtlId &&
        cartItem.OrderRate === item.OrderRate &&
        cartItem?.BookingTypeName === item?.BookingTypeName
    ); // check if the item is already in the cart

    if (isItemInCart?.OrderQty > 1) {
      await dispatch(
        changeKioskOrderDetails(
          KioskOrderDetails?.map(
            (
              cartItem // if the item is already in the cart, increase the quantity of the item
            ) =>
              cartItem.ProdId === item.ProdId &&
                cartItem.InwardDtlId === item.InwardDtlId &&
                cartItem.OrderRate === item.OrderRate &&
                cartItem?.BookingTypeName === item?.BookingTypeName
                ? {
                  ...cartItem,
                  OrderQty: cartItem.OrderQty - 1,
                  TotalAmt: (cartItem.OrderQty - 1) * cartItem.OrderRate,
                  TaxAmt: (
                    ((cartItem.OrderQty - 1) *
                      cartItem.OrderRate *
                      cartItem.TaxPercentage) /
                    (100 + cartItem.TaxPercentage)
                  ).toFixed(2),
                  WithoutTaxRate:
                    (cartItem.OrderQty - 1) * cartItem.OrderRate -
                    (
                      ((cartItem.OrderQty - 1) *
                        cartItem.OrderRate *
                        cartItem.TaxPercentage) /
                      (100 + cartItem.TaxPercentage)
                    ).toFixed(2),
                }
                : cartItem // otherwise, return the cart item
          )
        )
      );
    } else {
      await dispatch(
        changeKioskOrderDetails(
          KioskOrderDetails?.filter(
            (cartItem) =>
              !(
                cartItem.ProdId === item.ProdId &&
                cartItem.InwardDtlId === item.InwardDtlId &&
                cartItem.OrderRate === item.OrderRate
              )
          )
        )
      );
    }
  };
  return (
    <div className="KioskOrderList3-master">
      <div
        className="KioskOrderList3-main3"
        style={{ backgroundColor: getKioskLightColourdata }}
      >
        {/* header area  */}

        <KioskHeader
          KioskThemeData={KioskThemeData}
          SessionDtl={props?.SessionDtl}
        />

        <div
          className={
            props?.Footer === '3'
              ? 'KioskOrderList3-scrolling1'
              : 'KioskOrderList3-scrolling'
          }
        >
          <div className="KioskOrderList3-ordercard-main3">
            {KioskOrderDetails?.map((item) => (
              <div
                className="KioskOrderList3-ordercards"
                style={{ position: 'relative' }}
              >
                <div className="OrderViewCardIcon">
                  {item?.BookingTypeName == 'Dine In' ? (
                    <PozoDineInIcon
                      style={{
                        height: '25px',
                        width: '25px',
                        color: '#40AF7A',
                      }}
                    />
                  ) : (
                    <TakeAway
                      style={{
                        height: '25px',
                        width: '25px',
                        color: '#8D765B',
                      }}
                    />
                  )}
                </div>
                <div className="dish-img3">
                  <img
                    src={item?.ProdLogo ? item?.ProdLogo : horizontal}
                    alt="item image"
                  />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div className="KioskOrderList3-dishname-prize">
                    <p style={{ color: 'black' }}>
                      {item?.ProdName} &nbsp;{' '}
                      {item.BrandName !== null ? item.BrandName : ''}
                      <div style={{ textWrap: 'nowrap', color: 'black' }}>
                        {' '}
                        (
                        {!item?.ProdVariantName?.toLowerCase().includes(
                          'variant'
                        ) && (
                            <span style={{ color: 'black' }}>
                              {item?.ProdVariantName}{' '}
                            </span>
                          )}{' '}
                        {item?.Size}{' '}
                        {item?.SinglePc == 'Y' ? 'PCS' : item?.UomName}
                      </div>
                      )
                    </p>
                    <span>
                      {' '}
                      <MdCurrencyRupee
                        size={18}
                        style={{ marginRight: '-4px', marginBottom: '-3px' }}
                      />
                      {item?.TotalAmt}
                    </span>
                    <div className="KioskOrderList3-add-remove">
                      <div className="add-remove">
                        <span onClick={() => decrease(item)}> −</span>
                        <p>{item?.OrderQty}</p>
                        <span
                          style={{
                            pointerEvents:
                              item?.StockAvailable === 'Y'
                                ? item?.BalanceQty <= item?.OrderQty && 'none'
                                : '',
                            opacity:
                              item?.StockAvailable === 'Y'
                                ? item?.BalanceQty <= item?.OrderQty && '30%'
                                : '',
                          }}
                          onClick={() => increase(item)}
                        >
                          {' '}
                          +{' '}
                        </span>

                        <div
                          className="remove"
                          onClick={() => removeFromCart(item)}
                        >
                          <RiDeleteBin6Line />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div
          className={
            props?.Footer === '3'
              ? 'KioskOrderList3-addmore-footer3'
              : 'KioskOrderList3-addmore'
          }
          onClick={() => BackToCategory()}
          style={{ backgroundColor: getKioskLightColourdata }}
        >
          {' '}
          <p>Add More + </p>
        </div>

        <div>
          {props?.Footer === '1' && (
            <KioskFooter SessionDtl={props?.SessionDtl} />
          )}
          {props?.Footer === '2' && (
            <>
              <div
                style={{
                  position: 'fixed',
                  bottom: 0,
                  width: '100%',
                  background: 'white',
                  padding: '1rem 0rem',
                }}
              >
                <KioskFooter2 SessionDtl={props?.SessionDtl} />
              </div>
            </>
          )}
          {props?.Footer === '3' && (
            <>
              <div
                style={{
                  position: 'fixed',
                  bottom: 0,
                  width: '100%',
                  background: 'white',
                  padding: '1rem 0rem',
                }}
              >
                <KioskFooter3 SessionDtl={props?.SessionDtl} />
              </div>
            </>
          )}
        </div>
      </div>
      <div className={`Item3Warning ${maxLimitExceeded ? 'showing' : ''}`}>
        <p>
          <IoIosWarning size={30} color='#b99400' />Maximum Quantity ({maxQtyLimit}) Reached
        </p>
      </div>
    </div>
  );
};

export default KioskOrderView;
