import { useCallback, useEffect, useState } from 'react';
import { DefaultModal } from '../../../Components/Modal/DefaultModal';
import Denomination from '../../Reports/Denomination/Denomination';
import { Tables } from '../../../Components/Tables/Table';
import { dateTimeFormatChange, getSession } from '../../../Services/Others';
import { IoClose } from 'react-icons/io5';
import './RetailBookingClosing.scss';
import { useDispatch } from 'react-redux';
import { Messages } from '../../../Components/Notifications/Messages';
import Buttons from '../../../Components/Forms/Buttons';
import { ArrowRightOutlined } from '@ant-design/icons';
import {
  getRetailPaymentClosing,
  PostBookingClose,
} from '../../../Features/BookingScreen/RetailBookingClose';
import { getBookingStatus } from '../../../Features/Payment/PaymentReceivedRetail/PaymentReceivedRetail';
import { PreferenceData } from '../../../Features/BookingScreen/BookingData/BookingData';
import { useSelector } from 'react-redux';

const RetailBookingClosing = (props) => {
  const dispatch = useDispatch();
  const UserType = getSession('UserType');
  const preferenceDatas = useSelector(PreferenceData);
  const allowDecimal = preferenceDatas?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
  const CompId = getSession('CompId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const BranchId = getSession('BranchId');
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [PaymentClosingData, setPaymentClosingData] = useState([]);
  const [TotalCashInHand, setTotalCashInHand] = useState(0);
  console.log(PaymentClosingData, 'PaymentClosingData');
  const [ReceivedAmountopen, setReceivedAmountOpen] = useState(false);
  const [SettlementDetails, setSettlementDetails] = useState(false);
  const [DenominationOpen, setDenominationOpen] = useState(false);
  const [page, setpage] = useState(1);
  const [denominationData, setDenominationData] = useState({
    Amounts: {},
    OverAllTotal: 0,
  });
  useEffect(() => {
    getWholeSaleClosingList();
  }, []);
  const getWholeSaleClosingList = async () => {
    let data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: UserId,
    };
    let response = await dispatch(getRetailPaymentClosing(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setPaymentClosingData(response?.data?.data);
      let data = response?.data?.data;
      let TotalCashCal =
        parseInt(data?.OverAllCashAmount) + parseInt(data?.ReceivedAmount);
      setTotalCashInHand(TotalCashCal);
    } else {
      setPaymentClosingData([]);
    }
  };
  const OpenReceivedAmount = () => {
    setReceivedAmountOpen(!ReceivedAmountopen);
  };
  const OpenSettlementDetails = () => {
    setSettlementDetails(!SettlementDetails);
  };
  const OpenDenomination = async () => {
    setDenominationOpen(true);
    //  const PostData = {
    //             "UserId": UserId,
    //             "ScreenType": "Payment",
    //             "ScreenStatus": "Close",
    //             "OpeningBalance": 0,
    //             "ClosingBalance": 0,
    //             "AppId": AppId,
    //             "CompId": CompId,
    //             "BranchId": BranchId,
    //             "CreatedBy": UserId,
    //         }
    //         let WsPostresponse = await dispatch(WSBookingPost(PostData)).unwrap();
    //         if(WsPostresponse.data?.statusCode == 1){

    //         }
    //         else{
    //             setMessageType("error");
    //             setMessageData(WsPostresponse.data?.response);
    //         }
  };

  const DenominationClose = () => {
    setDenominationOpen(false);
  };
  const handleDenominationChange = (data) => {
    setDenominationData(data);
  };
  const ReceivedAmtcolumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Name',
      key: 'UserName',
      dataIndex: 'UserName',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>
          {record?.UserRole === 'Admin'
            ? `${record?.UserName ? record?.UserName : record?.UserMobile} (Admin)`
            : record?.UserName
              ? record?.UserName
              : record?.UserMobile}
        </a>
      ),
    },
    // {
    //     title: "Date",
    //     key: "Date",
    //     dataIndex: "Date",
    //     render: (productDetails, record) => (
    //         <a
    //             style={{ color: "black" }}
    //         >
    //             {dateTimeFormatChange(record?.Date)}
    //         </a>
    //     ),
    // },
    // ...(PaymentType !== "O"
    //     ? [
    {
      title: 'Payment Type',
      key: 'PaymentType',
      dataIndex: 'PaymentType',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>{record?.PaymentType}</a>
      ),
    },
    //       ]
    //     : []),
    {
      title: 'Amount',
      key: 'Amount',
      dataIndex: 'Amount',
      align: 'right',
      render: (productDetails, record) => (
        <a
          style={{
            color: record?.ReceivedAmount < 0 ? 'red' : 'green',
          }}
        >
          {Math.abs(record?.ReceivedAmount)}
        </a>
      ),
    },
  ];
  const SupplierDtlcolumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Name',
      key: 'UserName',
      dataIndex: 'UserName',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>
          {record?.CustSuppName
            ? record?.CustSuppName
            : record?.CustShortName
              ? record?.CustShortName
              : record?.CustSuppMobile}
        </a>
      ),
    },
    // {
    //     title: "Date",
    //     key: "Date",
    //     dataIndex: "Date",
    //     render: (productDetails, record) => (
    //         <a
    //             style={{ color: "black" }}
    //         >
    //             {dateTimeFormatChange(record?.Date)}
    //         </a>
    //     ),
    // },

    {
      title: 'Payment Type',
      key: 'PaymentType',
      dataIndex: 'PaymentType',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>{record?.PaymentType}</a>
      ),
    },

    {
      title: 'Amount',
      key: 'Amount',
      dataIndex: 'Amount',
      align: 'right',
      render: (productDetails, record) => (
        <a
          style={{
            color: record?.ReceivedAmount < 0 ? 'red' : 'green',
          }}
        >
          {Math.abs(record?.ReceivedAmount)}
        </a>
      ),
    },
  ];
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const handlePageChange = (current) => {
    setpage(current);
  };
  const PostDenomination = async () => {
    console.log(denominationData, 'denominationData');
    const mappedArray = Object.entries(denominationData?.Amounts || {}).map(
      ([denomination, count]) => ({
        Denomination: parseInt(denomination, 10),
        DenominationCount: count,
        DenominationAmount: parseInt(denomination, 10) * count,
      })
    );
    let Postdata = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
      UserId: UserId,
      BookingDate: new Date(),
      ServiceTotal:
        parseInt(PaymentClosingData?.BalanceCash) +
        parseInt(PaymentClosingData?.BalanceCard) +
        parseInt(PaymentClosingData?.BalanceUpi),
      ScreenType: 'Booking',
      ScreenStatus: 'Close',
      DenominationDetails: mappedArray?.filter(
        (item) => item.DenominationCount !== 0
      ),
      CreatedBy: UserId,
    };
    let PostWSDenomination = await dispatch(
      PostBookingClose(Postdata)
    ).unwrap();
    if (PostWSDenomination?.data?.statusCode == 1) {
      setMessageData('Booking Closed Successfully');
      setMessageType('success');
      props.PaymentClose();
      let data = {
        AppId: AppId,
        CompId: CompId,
        BranchId: BranchId,
        UserId: UserId,
      };
      await dispatch(getBookingStatus(data)).unwrap();
    } else {
      setMessageType('error');
      setMessageData('Booking Not Closed ');
    }
  };

  function safeRound(amountStr) {
    if (amountStr == null) return allowDecimal ? '0.00' : '0';

    const cleaned = String(amountStr).replace(/[^0-9.-]+/g, '');
    const num = Number(cleaned);

    if (isNaN(num)) return allowDecimal ? '0.00' : '0';

    return allowDecimal ? num.toFixed(2) : Math.round(num).toString();
  }

  return (
    <div className="BookingCloseModal">
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />

      <DefaultModal
        open={props.PaymentOpen}
        title={'Booking Close'}
        handleCancel={props.PaymentClose}
        footer={false}
        width={700}
        children={
          <div className="PaymentClosingOverAll">
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div className="PaymentClosingOverAll-sub">
                <div>
                  {' '}
                  Received Amount ={' '}
                  <span style={{ color: '#28AA3A', cursor: 'pointer' }}>
                    {safeRound(PaymentClosingData?.ReceivedAmount)}
                  </span>
                </div>
                <div>
                  Cash Amount ={' '}
                  <span style={{ color: '#28AA3A', cursor: 'pointer' }}>
                    {safeRound(PaymentClosingData?.OverAllCashAmount)}
                  </span>
                </div>
                <div>
                  Card Amount ={' '}
                  <span style={{ color: '#28AA3A', cursor: 'pointer' }}>
                    {safeRound(PaymentClosingData?.OverAllCardAmount)}
                  </span>
                </div>
                <div>
                  UPI Amount ={' '}
                  <span style={{ color: '#28AA3A', cursor: 'pointer' }}>
                    {safeRound(PaymentClosingData?.OverAllUpiAmount)}
                  </span>
                </div>

                <div>
                  Total Cash In Hand ={' '}
                  <span style={{ color: '#28AA3A' }}>
                    {safeRound(TotalCashInHand)}
                  </span>
                </div>
              </div>
              <div>
                <>
                  {/* <div className="PaymentTableClose" onClick={DenominationClose}>
                                        <IoClose size={15} />  
                                    </div> */}
                  <div style={{ width: '300px' }}>
                    <Denomination onchange={handleDenominationChange} />
                  </div>
                  {TotalCashInHand < parseInt(denominationData?.OverAllTotal) &&
                    parseInt(denominationData?.OverAllTotal) > 0 && (
                      <div
                        style={{
                          color: '#ff0000',
                          fontSize: '20px',
                          fontWeight: '600',
                          width: '100%',
                          textAlign: 'center',
                        }}
                      >
                        Amount is Mismatching
                      </div>
                    )}
                </>
              </div>
            </div>
            {ReceivedAmountopen && (
              <>
                <div className="PaymentTableClose" onClick={OpenReceivedAmount}>
                  <IoClose size={15} />
                </div>
                <div className="PaymentClose-Title">Received Details</div>
                <div className="Re-Print-table">
                  <Tables
                    columns={ReceivedAmtcolumns}
                    data={PaymentClosingData?.ReceivedAmtDtl}
                    dataSource={PaymentClosingData?.ReceivedAmtDtl}
                    // // data={PaidListData}
                    // // dataSource={PaidListData}
                    pagination={handlePageChange}
                  />
                </div>
              </>
            )}
            {SettlementDetails && (
              <>
                <div
                  className="PaymentTableClose"
                  onClick={OpenSettlementDetails}
                >
                  <IoClose size={15} />
                </div>
                <div className="PaymentClose-Title">Settlement Details</div>
                <div className="Re-Print-table">
                  <Tables
                    columns={SupplierDtlcolumns}
                    data={PaymentClosingData?.SupplierDtl}
                    dataSource={PaymentClosingData?.SupplierDtl}
                    // data={PaidListData}
                    // dataSource={PaidListData}
                    // pagination={handlePageChange}
                  />
                </div>
              </>
            )}
            <div className="PaymentCloseButtondiv">
              <button
                onClick={
                  parseInt(denominationData?.OverAllTotal) > 0
                    ? TotalCashInHand ==
                      parseInt(denominationData?.OverAllTotal)
                      ? PostDenomination
                      : ''
                    : PostDenomination
                }
                className="PaymentCloseButton"
                style={{
                  pointerEvents:
                    parseInt(denominationData?.OverAllTotal) > 0
                      ? TotalCashInHand !=
                        parseInt(denominationData?.OverAllTotal)
                        ? 'none'
                        : ''
                      : '',
                  opacity:
                    parseInt(denominationData?.OverAllTotal) > 0
                      ? TotalCashInHand !=
                        parseInt(denominationData?.OverAllTotal)
                        ? '0.5'
                        : ''
                      : '',
                }}
              >
                {' '}
                Payment Close
              </button>
            </div>
            <div></div>
          </div>
        }
      ></DefaultModal>
    </div>
  );
};
export default RetailBookingClosing;
