import React, { useEffect, useState, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { Switch, Tooltip, Form, DatePicker } from 'antd';
import moment from 'moment';
import { DatePicProd } from '../../../Components/Forms/DatePickerProduct.jsx';
import { Tables } from '../../../Components/Tables/Table';
import { BiSolidPrinter, BiUpArrowCircle } from 'react-icons/bi';
import Denomination from '../Denomination/Denomination';
import { Popover } from 'antd';
import '../../../Styles/Reports/DateWiseReport/DateWiseReport.scss';
import { changeBreadCrumb } from '../../../Features/AppPage/CenterPage';
import {
  getDatewiseReport,
  getPreferenceData,
  PreferenceData,
  UserDataBasedOnBranchId,
  wholesalegetDatewiseReport,
} from '../../../Features/BookingScreen/BookingData/BookingData';
import { getSession, printDiv } from '../../../Services/WSOthers';
import DatewiseReportPdf from '../../paymentpdfPage/DateWiseReportPdf';
import { DropDowns } from '../../../Components/Forms/DropDown.jsx';
import { isMobile } from 'react-device-detect';
import logo from '../../../Images/pozologoimg.png';
import { RadioGrpButton } from '../../../Components/Forms/RadioGroup.jsx';
import { IoSearch } from 'react-icons/io5';
import { ExtractDateFormate } from '../../../Services/Others.js';
import { useSelector } from 'react-redux';
import { ReportMobilePDFPrint } from '../../paymentpdfPage/ReportMobilePDFPrint.js';
import dayjs from 'dayjs';
const { RangePicker } = DatePicker;

const subDirectory = import.meta.env.BASE_URL;

const DateWiseReport = () => {
  const [open, setOpen] = useState(false);
  const formRef = useRef();
  const dispatch = useDispatch();
  const SettingDataSelector = useSelector(PreferenceData);
  const [datewiseData, setDatewiseData] = useState();
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserRole = getSession('UserType');
  const AppId = getSession('AppId');
  const AppType =
    getSession('AppType')?.toLowerCase() == 'wholesale' ? true : false;
  const [OrderFromDate, setOrderFromDate] = useState();
  const [OrderToDate, setOrderToDate] = useState();
  const [UserId, setUserId] = useState(
    UserRole != 'Employee' ? 0 : getSession('UserId')
  );
  const [userDropDown, setuserDropDown] = useState([]);
  const [selectedUserData, setSelectedUserData] = useState(null);
  const [dataSource, setdataSource] = useState([]);
  const [page, setpage] = useState(1);
  const [receiptText, setreceiptText] = useState(null);
  const [WholeDataSource, setWholeDataSource] = useState([]);
  const [Selecttype, setSelecttype] = useState('A');
  const [TotalCashInHand, setTotalCashInHand] = useState([]);
  const [allowDecimal, setAllowDecimal] = useState(false);
  const [openDenomination, setOpenDenomination] = useState(false);
  const [denominationData, setDenominationData] = useState({
    Amounts: {},
    OverAllTotal: 0,
  });
  const MobileA4Print = SettingDataSelector?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "mobilea4" && setting?.SettingValue === 'Y');
  console.log(MobileA4Print, 'MobileA4PrintMobileA4Print');

  useEffect(() => {
    if (dataSource?.length > 0) {
      mobileDateWisePrintFun(dataSource);
    }
  }, [dataSource]);
  useEffect(() => {
    if (WholeDataSource?.length > 0) {
      mobileDateWisePrintFun(WholeDataSource);
    }
  }, [WholeDataSource]);

  const reprintDate = (date) => {
    const salesDate = new Date(date);
    const formattedDate = salesDate.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
    return formattedDate;
  };
  const formatAmount = (value) => {
    return allowDecimal ? parseFloat(value || 0).toFixed(2) : Math.round(value || 0);
  };
  const mobileDateWisePrintFun = async (data) => {


    const Dataa = ["Cash", "Upi", "Card", "Credit"]?.map(method => {
      const amountKey = `${method}Amount`;
      const countKey = `${method}Count`;
      let TableData = AppType ? WholeDataSource : dataSource;
      const total = TableData?.reduce((acc, entry) => {
        acc.amount += entry[amountKey] || 0;
        acc.count += entry[countKey] || 0;
        return acc;
      }, { amount: 0, count: 0 });

      return {
        PaymentMethod: method,
        CountOfPaymentType: total.count,
        NetAmount: total.amount
      };
    })?.filter(entry => entry.NetAmount > 0);

    let Tabledata = Dataa?.map((data, index) => {
      const snoSpacing = Math.max(0, 3 - String(index + 1).length);
      // Calculate dynamic spacing for Rate
      const rateSpacing = Math.max(0, 9 - String(data?.NetAmount).length);
      const QtySpacing = Math.max(
        0,
        3 - String(data?.CountOfPaymentType).length
      );

      // Generate formatted string with dynamic spacings
      const formattedString =
        ' '.repeat(snoSpacing) +
        parseInt(index + 1) +
        '  ' +
        (data?.PaymentMethod + ' '.repeat(22)).substring(0, 22) +
        '  ' +
        ' '.repeat(QtySpacing) +
        String(data?.CountOfPaymentType) +
        ' ' +
        ' '.repeat(rateSpacing) +
        String(data?.NetAmount) +
        ' ' +
        '\n';

      return formattedString;
    });
    const OrderSpace = Math.max(
      0,
      6 - String(datewiseData?.[0]?.Orders).length
    );
    const Billamountspace = Math.max(
      0,
      6 -
      String(
        (AppType
          ? datewiseData?.[0]?.WholeSaleExpenseNetAmount
          : datewiseData?.[0]?.TotalBillAmount
        )?.toFixed(2)
      ).length
    );
    const Taxamountspace = Math.max(
      0,
      6 -
      String(
        (AppType
          ? datewiseData?.[0]?.WholeSaleExpenseTaxAmount
          : datewiseData?.[0]?.TaxAmount
        )?.toFixed(2)
      ).length
    );
    const Chargesamountspace = Math.max(
      0,
      6 - String(datewiseData?.[0]?.TotalExtraChargeAmount?.toFixed(2)).length
    );
    const Preorderamountspace = Math.max(
      0,
      6 - String(datewiseData?.[0]?.PreOrderNetAmount?.toFixed(2)).length
    );
    const Discountamountspace = Math.max(
      0,
      6 -
      String(
        (AppType
          ? datewiseData?.[0]?.WholeSaleExpenseTotalOverallDisc
          : datewiseData?.[0]?.TotalOfferAmount
        )?.toFixed(2)
      ).length
    );
    const Netamountspace = Math.max(
      0,
      6 -
      String(
        (AppType
          ? datewiseData?.[0]?.WholeSaleExpenseNetAmount
          : datewiseData?.[0]?.TotalNetAmount
        )?.toFixed(2)
      ).length
    );
    var data = datewiseData && datewiseData[0] ? datewiseData[0] : {};
    var receiptTextdata =
      "[C]<b><font size='big'>Datewise Sales</font></b>\n" +
      '[L]<b>From Date :' +
      reprintDate(OrderFromDate) +
      '[R]<b> To Date :' +
      reprintDate(OrderToDate) +
      '</b>\n' +
      '[C]------------------------------------------------\n' +
      '[L]<b>S.No   Payment Type       Count   Amount</b>[L]\n' +
      '[C]------------------------------------------------\n' +
      Tabledata.join('') +
      '[C]<b>------------------------------------------------</b>\n' +
      '[R]<b>Orders:' +
      (data?.Orders || 0) +
      ' '.repeat(OrderSpace) +
      '</b>\n' +
      '[R]<b>Bill Amount:' +
      parseFloat(
        !AppType
          ? (data?.TotalBillAmount || 0) -
          (data?.TotalExtraChargeAmount || 0) +
          (data?.TotalOfferAmount || 0)
          : data?.WholeSaleExpenseNetAmount || 0
      ).toFixed(2) +
      ' '.repeat(Billamountspace) +
      '</b>\n';

    // Tax
    if ((AppType ? data?.WholeSaleExpenseTaxAmount : data?.TaxAmount) > 0) {
      receiptTextdata +=
        '[R]<b>Tax:' +
        parseFloat(
          AppType ? data?.WholeSaleExpenseTaxAmount : data?.TaxAmount
        ).toFixed(2) +
        ' '.repeat(Taxamountspace) +
        '</b>\n';
    }

    // Charges
    if ((data?.TotalExtraChargeAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Charges:' +
        parseFloat(data?.TotalExtraChargeAmount).toFixed(2) +
        ' '.repeat(Chargesamountspace) +
        '</b>\n';
    }

    // Preorder
    if ((data?.PreOrderNetAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Preorder:' +
        parseFloat(data?.PreOrderNetAmount).toFixed(2) +
        ' '.repeat(Preorderamountspace) +
        '</b>\n';
    }

    // Discount
    var discountAmount = AppType
      ? data?.WholeSaleExpenseTotalOverallDisc
      : data?.TotalOfferAmount;
    if ((discountAmount || 0) > 0) {
      receiptTextdata +=
        '[R]<b>Discount(-):' +
        parseFloat(discountAmount).toFixed(2) +
        ' '.repeat(Discountamountspace) +
        '</b>\n';
    }

    receiptTextdata +=
      '[L]<b>------------------------------------------------</b>\n' +
      '[R]<b>Net:' +
      parseFloat(
        Math.round(
          AppType
            ? datewiseData?.[0]?.WholeSaleExpenseNetAmount || 0
            : datewiseData?.[0]?.TotalNetAmount +
            (datewiseData?.[0]?.PreOrderNetAmount || 0) || 0
        )
      ).toFixed(2) +
      ' '.repeat(Netamountspace) +
      '</b>\n';

    setreceiptText(receiptTextdata);
  };
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
  ];
  const style = `<style>
  @import url('https://fonts.googleapis.com/css2?family=Podkova:wght@400..800&display=swap');  
             
           @media print {
                     body { 
                         font-family:"Podkova", serif; 
                         font-size: 13px; /* Adjust font size for print */
                         margin: 0;
                         padding: 0;
                     }
                 }    
          * {
                     margin: 0;
                     padding: 0;
                     box-sizing: border-box;
                     font-family:"Podkova", serif; 
                 }
  .imgDiv {
    height: 50px;
    display: flex;
    justify-content: center;
  }
  .Dates {
    width: 93%;
    display: flex;
    justify-content: space-between;
    alignItems: center;
    margin-left: 15px;
  }
  .DatesStyle {
    display: flex;
    gap: 0.3rem;
  }
  
  .p {
    font-size: 10px;
  }
  
  .totalAmount {
    width: 95%;  
    display: flex;
    justify-content: flex-end;
    font-size: 15px;
    margin-top: 5px;
  }
  .totaldetails {
    width: 95%;  
    display: flex;
    justify-content: flex-end;
    font-size: 10px;
  }
  .Table,
  .th,
  .td {
    border: 1px solid black;
    border-collapse: collapse;
      font-size: 10px;
  }
  .td {
    padding: 4px
  }
  .th {
    padding: 4px
  }
  
  .DateWiseSales {
    display: flex;
    justify-content: center;
    font-size: 12px;
    font-weight: 500;
  }
  .Table {
    width: 95%;
  }
  .Pdf-Table-Div {
    margin-left: 15px;
  }

    </style>`;

  useEffect(() => {
    getPreference()
    dispatch(changeBreadCrumb({ items: items }));
    fetchInitialData();
    if (UserRole != 'Employee') {
      userDropData();
    }
  }, []);

  const getPreference = async () => {
    const data = { AppId: AppId, CompId: CompId, BranchId: BranchId };
    const { data: res } = await dispatch(getPreferenceData(data)).unwrap()
    const decimalSetting = res?.data?.[0]?.SettingDtlDetails?.find((setting) => setting?.SettingIdName?.toLowerCase() === "decimal" && setting?.SettingValue === 'Y');
    if (decimalSetting) {
      setAllowDecimal(true)
    }
  }

  const userDropData = async () => {
    const gettinguserDropDown = await dispatch(
      UserDataBasedOnBranchId(BranchId)
    ).unwrap();
    if (gettinguserDropDown?.data?.statusCode === 1) {
      let finaluserDropDown = gettinguserDropDown?.data?.data?.filter(
        (value) => value.ActiveStatus === 'A'
      );
      finaluserDropDown.push({ UserId: 0, UserName: 'All User' });
      // let admindtl = {"UserId":finaluserDropDown?.[0]?.AdminDetail?.[0]?.UserId,
      // "UserName":finaluserDropDown?.[0]?.AdminDetail?.[0]?.UserName+' ('+"Admin"+')'};
      // finaluserDropDown.push(admindtl);

      setSelectedUserData(0);
      formRef.current?.setFieldsValue({
        UserId: 0,
      });

      setuserDropDown(finaluserDropDown);
    }
  };

  const fetchInitialData = async () => {
    let currentDate = new Date().toJSON().slice(0, 10);
    formRef?.current?.setFieldsValue({
      dateRange: [dayjs(currentDate, 'YYYY-MM-DD'), dayjs(currentDate, 'YYYY-MM-DD')],
    });
    setOrderFromDate(currentDate + 'T00:00:00');
    setOrderToDate(currentDate + 'T23:59:59');
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      OrderFromDate: currentDate,
      OrderToDate: currentDate,
      UserId: UserRole != 'Employee' ? 0 : UserId,
      filterType: Selecttype,
    };

    if (AppType) {
      let response = await dispatch(wholesalegetDatewiseReport(data)).unwrap();
      if (response?.data?.statusCode === 1) {
        setDatewiseData(response?.data?.data);
        // setdataSource(response?.data?.data?.[0]?.OrderDetails);
        setWholeDataSource(
          response?.data?.data?.[0]?.WholeSaleExpenseOrderDetails
        );
      } else {
        setDatewiseData([]);
        setdataSource([]);
      }
    } else {
      let response = await dispatch(getDatewiseReport(data)).unwrap();
      if (response?.data?.statusCode === 1) {
        setDatewiseData(response?.data?.data);
        setdataSource(response?.data?.data?.[0]?.OrderDetails);
        setTotalCashInHand(response?.data?.data?.[0]?.OrderDetails);
      } else {
        setDatewiseData([]);
        setdataSource([]);
      }
    }
  };

  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();
  }

  function changeDateFormat(dateStr) {
    if (!dateStr || typeof dateStr !== 'string') return '';
    const dateParts = dateStr.split('-');
    if (dateParts.length !== 3) return '';
    return `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
  }

  // const columns = [
  //   {
  //     title: 'SI NO',
  //     dataIndex: 'SINO',
  //     key: 'SINO',
  //     align: 'center',
  //     render: (text, object, index) => (
  //       <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
  //     ),
  //   },
  //   {
  //     title: 'Payment Type',
  //     dataIndex: 'PaymentMethod',
  //     key: 'PaymentMethod',
  //   },
  //   {
  //     title: 'Date',
  //     dataIndex: 'Date',
  //     key: 'Date',
  //     render: (text) => (
  //       <span style={{ color: 'black' }}>{changeDateFormat(text)}</span>
  //     ),
  //   },
  //   {
  //     title: 'Count',
  //     dataIndex: 'TotalOrders',
  //     key: 'TotalOrders',
  //     align: 'right',
  //   },
  //   {
  //     title: 'Amount Collected',
  //     dataIndex: 'BillAmount',
  //     key: 'BillAmount',
  //     align: 'right',
  //     render: (text) => <span>{safeRound(text)}</span>,
  //   },
  // ];

  const onChange = (checked) => {
    setOpenDenomination(checked);
  };

  const hide = () => {
    setOpen(false);
  };
  const handleOpenChange = (newOpen) => {
    setOpen(newOpen);
  };


  const UserDropDownChange = async (e) => {
    setUserId(e);
    let mob = userDropDown?.filter((item) => item?.UserId === e);
    formRef.current?.setFieldsValue({
      UserId: e,
      MobileNo: mob?.[0]?.MobileNo,
    });
    setSelectedUserData(e);
  };

  const OrderDateRangeFetch = (dates, dateStrings) => {
    const [from, to] = dates || [];
    const [fromStr, toStr] = dateStrings || [];

    // Clear when picker cleared
    if (!from || !fromStr) {
      setOrderFromDate(undefined);
      formRef.current?.setFieldsValue({ Fromdate: undefined });
    } else {
      const DateFrom = `${fromStr.split('-').reverse().join('-')}T00:00:00`;
      // fromStr is in DD-MM-YYYY, convert to YYYY-MM-DD
      setOrderFromDate(DateFrom);
      formRef.current?.setFieldsValue({ Fromdate: DateFrom });
    }

    if (!to || !toStr) {
      setOrderToDate(undefined);
      formRef.current?.setFieldsValue({ Todate: undefined });
    } else {
      // set To as end of day for inclusive queries
      const toIso = `${toStr.split('-').reverse().join('-')}T23:59:59`;
      setOrderToDate(toIso);
      formRef.current?.setFieldsValue({ Todate: toIso });
    }
  };
  const Print = async () => {
    let LogoImage = '';
    let OrderId = '';
    let UpiId = '';
    let TokenData = '';
    let FooterPrint = '';
    if (isMobile) {
      if (MobileA4Print) {
        ReportMobilePDFPrint({
          printId: 'RePrint',
          printStyle: style,
        });
      }
      else {
        var textEncoded = encodeURI(receiptText);
        var TypeCheck = 'PrintReceipt';
        var scheme = 'pozoprinter';
        var packageName = 'com.example.pozoprinter';

        window.location.href =
          scheme +
          '://' +
          textEncoded +
          '#Intent;scheme=' +
          scheme +
          ';package=' +
          packageName +
          'ImgS' +
          LogoImage +
          'ImgE' +
          TypeCheck +
          'TokenS' +
          TokenData +
          'TokenE' +
          'EstimateS' +
          '' +
          'EstimateE' +
          'HasFooterTextS' +
          FooterPrint +
          'HasFooterTextE' +
          ';end;';
      }
    } else {
      await printDiv('RePrint', style);
    }
  };

  const onFinish = async (values) => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      OrderFromDate: OrderFromDate?.split('T')?.[0],
      OrderToDate: OrderToDate?.split('T')?.[0],
      UserId: UserId,
      filterType: Selecttype,
    };

    if (AppType) {
      let response = await dispatch(wholesalegetDatewiseReport(data)).unwrap();
      if (response?.data?.statusCode === 1) {
        setDatewiseData(response?.data?.data);
        setWholeDataSource(
          response?.data?.data?.[0]?.WholeSaleExpenseOrderDetails
        );
      } else {
        setDatewiseData([]);
        setdataSource([]);
        setWholeDataSource([]);
      }
    } else {
      let response = await dispatch(getDatewiseReport(data)).unwrap();
      if (response?.data?.statusCode === 1) {
        setDatewiseData(response?.data?.data);
        setdataSource(response?.data?.data?.[0]?.OrderDetails);
      } else {
        setDatewiseData([]);
        setdataSource([]);
        setWholeDataSource([]);
      }
    }
  };
  const TotalBill = AppType
    ? datewiseData?.[0]?.WholeSaleExpenseNetAmount
    : datewiseData?.[0]?.TotalBillAmount;

  const handleDenominationChange = (data) => {
    setDenominationData(data);
  };

  const selectdataType = (e) => {
    setSelecttype(e);
    // formRef.current?.resetFields()
  };

  return (
    <div className="DateWiseReport-container">
      <div style={{ display: 'none' }}>
        <DatewiseReportPdf
          OrderFromDate={OrderFromDate?.split('T')?.[0]}
          OrderToDate={OrderToDate?.split('T')?.[0]}
          dataSource={AppType ? WholeDataSource : dataSource}
          TotalBill={TotalBill}
          datewiseData={datewiseData}
          TotalOrders={
            AppType
              ? datewiseData?.[0]?.WholeSaleExpenseCount
              : datewiseData?.[0]?.Orders
          }
          TotalBillAmount={TotalBill}
          TaxAmount={
            AppType
              ? datewiseData?.[0]?.WholeSaleExpenseTaxAmount
              : datewiseData?.[0]?.TaxAmount
          }
          TotalNetAmount={
            AppType
              ? datewiseData?.[0]?.WholeSaleExpenseNetAmount
              : datewiseData?.[0]?.TotalNetAmount
          }
          TotalPreOrderAmount={datewiseData?.[0]?.PreOrderNetAmount}
          TotalCharges={datewiseData?.[0]?.TotalExtraChargeAmount}
          TotalDiscount={datewiseData?.[0]?.TotalOfferAmount}
          ReportName={''}
        />
      </div>
      <Form ref={formRef} onFinish={onFinish}>
        <div
          className="DateWiseReport-dateandheading"
          style={{ display: 'flex' }}
        >
          <p className="DateWiseReport-heading">Daily Sales</p>

          <div className="DateWiseReport-dateaAnd-buttons">
            <div
              className="DateWiseReport-Date-picker"
              style={{ display: 'flex', flexDirection: 'row', rowGap: '1rem' }}
            >
              <div className="DateWiseReport-datepic">
             <div className="DateWiseReport-DateFrom">
                 <Form.Item
                  name="dateRange"
                  initialValue={[dayjs(), dayjs()]} // ✅ Preselect today for both From and To
                  rules={[
                    {
                      required: true,
                      message: 'Please select From and To Dates',
                    },
                  ]}
                >
                  <RangePicker
                    format="DD-MM-YYYY"
                    allowClear
                    disabledDate={(current) => current && current > dayjs()} // Disable future dates
                    onChange={(dates, dateStrings) => {
                      OrderDateRangeFetch(dates, dateStrings);
                    }}
                    placeholder={['From Date', 'To Date']}
                  />
                </Form.Item>
             </div>
                <div className="datewise-userDropDown">
                  {UserRole != 'Employee' && (
                    <Form.Item
                      name="UserId"
                      rules={[
                        {
                          required: true,
                          message: 'Please Select User Name',
                        },
                      ]}
                    >
                      <DropDowns
                        options={userDropDown?.map((option) => ({
                          value: option?.UserId,
                          label: option?.UserName,
                        }))}
                        label={<label>User Name</label>}
                        id="UserId"
                        field="UserId"
                        fieldState={true}
                        fieldApi={true}
                        className="field-DropDown-Emp"
                        onChangeFunction={(e) => UserDropDownChange(e)}
                        isOnchanges={selectedUserData ? true : false}
                        valueData={selectedUserData}
                      // defaultValue={LastSelectConfig}
                      />
                    </Form.Item>
                  )}
                </div>
                <div>
                  <Form.Item name="Select">
                    <RadioGrpButton
                      content={[
                        { value: 'A', label: 'All' },
                        { value: 'I', label: 'Individual' },
                      ]}
                      fieldState={true}
                      defaultSelect={Selecttype}
                      onSelectFuntion={(e) => selectdataType(e)}
                      onClickFunction={(e) => selectdataType(e)}
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
            <div className="DateWiseReport-submit-prnt">
              <div>
                <Tooltip title="Submit to search">
                  <button
                    type="submit"
                    style={{
                      display: 'flex',
                      gap: '1rem',
                      alignItems: 'center',
                      fontFamily: 'Poppins, sans-serif',
                    }}
                    className="DateWiseReport-submit-btn"
                  >
                    SEARCH <IoSearch />
                  </button>
                </Tooltip>
              </div>

              <div>
                <Tooltip title="Print">
                  <BiSolidPrinter
                    className={
                      datewiseData?.[0]?.TotalNetAmount > 0
                        ? 'DateWiseReport-printerIcon'
                        : 'DateWiseReport-printerIcon-disabled'
                    }
                    onClick={Print}
                  />
                </Tooltip>
              </div>
            </div>
          </div>
        </div>

        <div className="DateWiseReport-coontent-body">
          <div
            className={
              openDenomination
                ? 'DateWiseReport-table-withDenom'
                : 'DateWiseReport-table-withoutDenom'
            }
          >
            <div className="DateWiseReport-table">
              <table className="custom-table">
                <thead>
                  <tr>
                    <th rowSpan="2" style={{ textAlign: 'center' }}>
                      S.No
                    </th>
                    {dataSource?.[0]?.Date && <th rowSpan="2" style={{ textAlign: 'center' }}>
                      Date
                    </th>}
                    <th colSpan="2" style={{ textAlign: 'center' }}>
                      Cash
                    </th>
                    <th colSpan="2" style={{ textAlign: 'center' }}>
                      UPI
                    </th>
                    <th colSpan="2" style={{ textAlign: 'center' }}>
                      Card
                    </th>
                    <th colSpan="2" style={{ textAlign: 'center' }}>
                      Credit
                    </th>
                    <th rowSpan="2" style={{ textAlign: 'center' }}>
                      Total
                    </th>
                  </tr>
                  <tr>
                    <th style={{ textAlign: 'center' }}>Count</th>
                    <th style={{ textAlign: 'center' }}>Amt</th>
                    <th style={{ textAlign: 'center' }}>Count</th>
                    <th style={{ textAlign: 'center' }}>Amt</th>
                    <th style={{ textAlign: 'center' }}>Count</th>
                    <th style={{ textAlign: 'center' }}>Amt</th>
                    <th style={{ textAlign: 'center' }}>Count</th>
                    <th style={{ textAlign: 'center' }}>Amt</th>
                  </tr>
                </thead>
                <tbody>
                  {(AppType ? WholeDataSource : dataSource)?.map((row, idx) => {
                    const {
                      Date,
                      CashCount = 0,
                      CashAmount = 0,
                      UpiCount = 0,
                      UpiAmount = 0,
                      CardCount = 0,
                      CardAmount = 0,
                      CreditCount = 0,
                      CreditAmount = 0,
                    } = row;

                    const date = Date ? ExtractDateFormate(Date) : '';
                    const totalAmt = [
                      CashAmount,
                      UpiAmount,
                      CardAmount,
                      CreditAmount,
                    ].reduce((sum, val) => sum + Number(val), 0);

                    return (
                      <tr key={Date + idx}>
                        <td style={{ textAlign: 'center' }}>{idx + 1}</td>
                        {dataSource?.[0]?.Date && <td style={{ textAlign: 'center' }}>{date}</td>}
                        <td style={{ textAlign: 'right' }}>{CashCount ?? 0}</td>
                        <td style={{ textAlign: 'right' }}>
                          {safeRound(CashAmount)}
                        </td>
                        <td style={{ textAlign: 'right' }}>{UpiCount ?? 0}</td>
                        <td style={{ textAlign: 'right' }}>
                          {safeRound(UpiAmount)}
                        </td>
                        <td style={{ textAlign: 'right' }}>{CardCount ?? 0}</td>
                        <td style={{ textAlign: 'right' }}>
                          {safeRound(CardAmount)}
                        </td>
                        <td style={{ textAlign: 'right' }}>{CreditCount ?? 0}</td>
                        <td style={{ textAlign: 'right' }}>
                          {safeRound(CreditAmount)}
                        </td>
                        <td style={{ textAlign: 'right' }}>
                          {safeRound(totalAmt)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {/* <div className="DateWiseReport-mobile-screen-Denomination">
              <p>Denomination:</p>
              <Popover
                // content={<a onClick={hide}>Close</a>}
                content={<Denomination />}
                trigger="click"
                open={open}
                onOpenChange={handleOpenChange}
              >
                <div className="DateWiseReport-popup-button">
                  <BiUpArrowCircle style={{ fontSize: "25px" }} />
                </div>
              </Popover>
            </div>
 */}

            <div className="DateWiseReport-Amount-Collected-container">
              {/* <div className="DateWiseReport-toggle-container">
                <p>Denomination</p> <Switch onChange={onChange} />
              </div> */}

              <div className="DateWiseReport-Amount-Collected-table">
                <table className="DateWiseReport-Amount-Collected-table-div">
                  <thead>
                    <tr>
                      <th>Orders</th>
                      <th>
                        {!AppType
                          ? datewiseData?.[0]?.Orders
                          : datewiseData?.[0]?.WholeSaleExpenseCount}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td>Bill Amount</td>
                      <td>
                        {!AppType
                          ? (datewiseData?.[0]?.TotalBillAmount || 0) -
                          (datewiseData?.[0]?.TotalExtraChargeAmount || 0) +
                          (datewiseData?.[0]?.TotalOfferAmount || 0)
                          : datewiseData?.[0]?.WholeSaleExpenseNetAmount}
                      </td>
                    </tr>
                    {!AppType
                      ? datewiseData?.[0]?.TaxAmount > 0 && (
                        <tr>
                          <td>Tax</td>
                          <td>{datewiseData?.[0]?.TaxAmount}</td>
                        </tr>
                      )
                      : datewiseData?.[0]?.WholeSaleExpenseTaxAmount > 0 && (
                        <tr>
                          <td>Tax</td>
                          <td>
                            {datewiseData?.[0]?.WholeSaleExpenseTaxAmount}
                          </td>
                        </tr>
                      )}
                    {datewiseData?.[0]?.TotalExtraChargeAmount > 0 && (
                      <tr>
                        <td>Charges</td>
                        <td>{datewiseData?.[0]?.TotalExtraChargeAmount}</td>
                      </tr>
                    )}
                    {datewiseData?.[0]?.PreOrderNetAmount > 0 && (
                      <tr>
                        <td>Preorder</td>
                        <td>{datewiseData?.[0]?.PreOrderNetAmount}</td>
                      </tr>
                    )}
                    {AppType
                      ? datewiseData?.[0]?.WholeSaleExpenseTotalOverallDisc >
                      0 && (
                        <tr>
                          <td>Discount(-)</td>
                          <td>
                            {
                              datewiseData?.[0]
                                ?.WholeSaleExpenseTotalOverallDisc
                            }
                          </td>
                        </tr>
                      )
                      : datewiseData?.[0]?.TotalOfferAmount > 0 && (
                        <tr>
                          <td>Discount(-)</td>
                          <td>{datewiseData?.[0]?.TotalOfferAmount}</td>
                        </tr>
                      )}

                    <p className="DateWiseReport-border-dashed"></p>
                    <tr>
                      <td className="DateWiseReport-netAmount">Net</td>
                      <td className="DateWiseReport-netAmount">
                        {AppType
                          ? safeRound(
                            datewiseData?.[0]?.WholeSaleExpenseNetAmount
                          ) || 0
                          : safeRound(
                            datewiseData?.[0]?.TotalNetAmount +
                            (datewiseData?.[0]?.PreOrderNetAmount || 0)
                          ) || 0}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          {openDenomination && (
            <div className="DateWiseReport-denomination-container">
              <div className="DateWiseReport-denomination">
                <>
                  <Denomination onchange={handleDenominationChange} />
                  {TotalCashInHand[0]?.PaymentMethod === 'Cash' &&
                    TotalCashInHand[0]?.NetAmount <
                    parseInt(denominationData?.OverAllTotal) &&
                    parseInt(denominationData?.OverAllTotal) > 0 && (
                      <div
                        className="amountMissmatch"
                        style={{
                          color: '#ff0000',
                          fontSize: '20px',
                          fontWeight: '600',
                          width: '100%',
                          textAlign: 'right',
                          backgroundColor: 'rgb(232, 236, 241)',
                        }}
                      >
                        Amount is Mismatching
                      </div>
                    )}
                </>
              </div>
            </div>
          )}
        </div>
      </Form>
    </div>
  );
};

export default DateWiseReport;
