import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Popconfirm, Drawer } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import PozoDineInIcon from '../KioskIcons/KioskDineIn';
import TakeAway from '../KioskIcons/KioskTakeAway';
import { IoIosArrowForward } from 'react-icons/io';
import { MdCurrencyRupee } from 'react-icons/md';
import {
  changeKioskCustomerMobileNo,
  changeKioskPageName,
  getKioskDarkColour,
  globalCurrentKioskPageName,
  globalSalesType,
} from '../../../Features/Kiosk/kiosk';
import {
  GlobalBookingTypeKiosk,
  GlobalKioskOrderDetails,
  GlobalOrderbtnClicked,
  GlobalPaymentgatewayRedirect,
  changeAllGlbStatustData,
  changeBookingType,
} from '../../../Features/BookingScreen/BookingData/KioskBookingData';
import OrderCart1 from '../OrderCart/OrderCart1';
import OrderCart2 from '../OrderCart/OrderCart2';
import OrderCart3 from '../OrderCart/OrderCart3';
import '../../../Styles/Kiosk/Components/KioskFooter3.scss';
import KioskPayment from '../Payment/KioskPaymentWithModal';

const KioskFooter3 = (props) => {
  const dispatch = useDispatch();
  const KioskOrderDetails = useSelector(GlobalKioskOrderDetails);
  const KioskCurrentPage = useSelector(globalCurrentKioskPageName);
  const BookingType = useSelector(GlobalBookingTypeKiosk);
  const getKioskDarkColourdata = useSelector(getKioskDarkColour);
  const getmobilepage = useSelector(GlobalPaymentgatewayRedirect);
  const SalesType = useSelector(globalSalesType);
  const [TotalTaxAmount, setTotalTaxAmount] = useState(null);
  const [TotalBillAmount, setBillAmount] = useState(null);
  const [TotalNetAmount, setTotalNetAmount] = useState(null);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const clicked = useSelector(GlobalOrderbtnClicked);
  const kioskTemplateData = props?.data;
  const sessionData = props?.SessionDtl;

  useEffect(() => {
    TotalCalculation();
  }, [KioskOrderDetails]);
  useEffect(() => {
    if (getmobilepage) {
      MobileNumberPage();
    }
  }, [getmobilepage]);
  const TotalCalculation = () => {
    const totalwithouttax = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.WithoutTaxRate || 0);
    }, 0);
    setBillAmount(parseFloat(totalwithouttax)?.toFixed(2));
    const totalPrice = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TotalAmt || 0);
    }, 0);
    setTotalNetAmount(parseFloat(totalPrice)?.toFixed(2));
    const totalTaxAmt = KioskOrderDetails?.reduce((accumulator, card) => {
      return accumulator + parseFloat(card.TaxAmt || 0);
    }, 0);
    setTotalTaxAmount(parseFloat(totalTaxAmt)?.toFixed(2));
  };

  const MobileNumberPage = async () => {
    setPaymentModalOpen(true);
  };
  const handleClick = () => {
    if (KioskCurrentPage === 'OrderView') {
      if (!clicked && KioskOrderDetails?.length > 0) {
        MobileNumberPage();
      }
    } else {
      dispatch(changeKioskPageName('OrderView'));
    }
  };

  const Oncancel = () => {
    dispatch(changeKioskPageName('initialPage'));
    dispatch(changeAllGlbStatustData());
    dispatch(changeKioskCustomerMobileNo(null));
    // clear all global val
  };

  // Drawer code

  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState('right');
  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
  // Change BookingType
  const ChangeType = async (Type) => {
    await dispatch(changeBookingType(Type));
  };
  const handlePaymentCancel = () => {
    setPaymentModalOpen(false);
    dispatch(changeKioskCustomerMobileNo(null));
  };
  return (
    <div className="KioskFooter3-master">
      <div className="KioskFooter3-main">
        {/* total code area  */}
        <div
          className="KioskFooter3-total"
          style={{
            justifyContent:
              KioskCurrentPage === 'OrderView'
                ? 'flex-end'
                : SalesType === 'B' || KioskOrderDetails?.length > 0
                  ? 'space-between'
                  : 'flex-end',
            padding: TotalTaxAmount > 0 ? '0.3rem 1rem' : '1rem 1rem',
          }}
        >
          <Drawer
            title="Order View"
            placement={placement}
            width={480}
            onClose={onClose}
            open={open}
            className="my-cls"
          >
            {kioskTemplateData?.['KioskOrderCart']?.[0] == 'OrderCart1' ? (
              <OrderCart1 KioskOrderDetails={KioskOrderDetails} />
            ) : kioskTemplateData?.['KioskOrderCart']?.[0] == 'OrderCart2' ? (
              <OrderCart2 KioskOrderDetails={KioskOrderDetails} />
            ) : kioskTemplateData?.['KioskOrderCart']?.[0] == 'OrderCart3' ? (
              <OrderCart3 KioskOrderDetails={KioskOrderDetails} />
            ) : null}
          </Drawer>
          {/* Change booking type */}
          {KioskCurrentPage !== 'OrderView' && (
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                cursor: 'pointer',
                gap: ' 1rem',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  cursor: 'pointer',
                  gap: '10px',
                }}
                onClick={() =>
                  BookingType === 'TakeAway' && ChangeType('Dine In')
                }
              >
                <PozoDineInIcon
                  className={
                    BookingType == 'Dine In'
                      ? 'BSBillingNav-icon-table pulse-element'
                      : 'BSBillingNav-icon'
                  }
                />
                <p style={{ fontSize: '12px', fontWeight: '600' }}>DineIn</p>
              </div>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  cursor: 'pointer',
                  gap: '10px',
                }}
                onClick={() =>
                  BookingType !== 'TakeAway' && ChangeType('TakeAway')
                }
              >
                <TakeAway
                  className={
                    BookingType != 'Dine In'
                      ? 'BSBillingNav-icon-table pulse-element'
                      : 'BSBillingNav-icon'
                  }
                />
                <p style={{ fontSize: '12px', fontWeight: '600' }}>TakeAway</p>
              </div>
            </div>
          )}

          {KioskOrderDetails?.length > 0 &&
            KioskCurrentPage !== 'OrderView' && (
              <div className="KioskFooter3-view-order" onClick={showDrawer}>
                View order{' '}
                <IoIosArrowForward style={{ marginBottom: '-2px' }} />
              </div>
            )}

          <div className="KioskFooter3-total-gst">
            <div className="gst-item">
              <p>Total Items :{KioskOrderDetails?.length}</p>

              <div>
                Bill Amount :
                <MdCurrencyRupee
                  size={16}
                  style={{ marginBottom: '-2px', marginRight: '-10px' }}
                />{' '}
                {TotalBillAmount}
              </div>
              {TotalTaxAmount > 0 && (
                <div>
                  Tax Amount :
                  <MdCurrencyRupee
                    size={16}
                    style={{ marginBottom: '-2px', marginRight: '-10px' }}
                  />{' '}
                  {TotalTaxAmount}
                </div>
              )}
            </div>

            <div className="total-amount-footer3">
              Total Amount :
              <MdCurrencyRupee
                size={30}
                style={{ marginBottom: '-4px', marginRight: '-5px' }}
              />{' '}
              {TotalNetAmount}
            </div>
          </div>
        </div>
        <div className="KioskFooter3-button">
          <Popconfirm
            description={
              <p
                style={{
                  fontSize: '18px',
                  fontWeight: '600',
                  paddingBottom: '1rem',
                }}
              >
                Are you sure, you want to cancel this order ?
              </p>
            }
            icon={
              <QuestionCircleOutlined
                style={{
                  color: '#fff',
                }}
              />
            }
            cancelText="No"
            okText="Yes"
            okButtonProps={{
              style: {
                width: '14rem',
                height: '2.5rem',
                borderRadius: '2rem',
                backgroundColor: '#FF3A3A',
                fontFamily: 'gilroy',
                fontWeight: '600',
                fontSize: '18px',
                border: 'none',
              },
              className: 'custom-ok-button',
            }}
            cancelButtonProps={{
              style: {
                width: '5rem',
                height: '2.5rem',
                borderRadius: '2rem',
                fontFamily: 'gilroy',
                fontWeight: '600',
                fontSize: '18px',
              },
              type: 'default',
              className: 'custom-cancel-button',
            }}
            overlayClassName="custom-popconfirm-overlay"
            onConfirm={() => Oncancel()}
          >
            <div className="cancel">cancel</div>
          </Popconfirm>
          <div
            className={
              KioskOrderDetails?.length > 0 && !clicked
                ? 'order-Enable'
                : 'order'
            }
            onClick={handleClick}
            style={{
              cursor:
                KioskOrderDetails?.length > 0 && !clicked
                  ? 'pointer'
                  : 'default',
              backgroundColor:
                KioskOrderDetails?.length > 0 && !clicked
                  ? getKioskDarkColourdata
                  : '#E1E1E1',
            }}
          >
            Order
          </div>
        </div>

        {paymentModalOpen && (
          <KioskPayment
            modalOpen={paymentModalOpen}
            handleCancel={handlePaymentCancel}
            sessionData={sessionData}
          />
        )}
      </div>
    </div>
  );
};

export default KioskFooter3;
