import { useState, useEffect, useCallback, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { Tables } from '../../Components/Tables/Table.jsx';
import FormHeader from '../PageComponents/FormHeader.jsx';
import Search from '../../Components/Forms/Search.jsx';
import {
  dateFormatChange,
  extractLastNumberOrderId,
  extractLastNumber,
  getSession,
  printDiv,
  dateTimeFormatChange,
} from '../../Services/WSOthers.js';
import { Messages } from '../../Components/Notifications/Messages.jsx';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';
import { Table } from 'antd';
import {
  getAbstractList,
  sellergetAbstractList,
} from '../../Features/WholeSale/WholeSaleAbstract.js';
import { BiSolidPrinter } from 'react-icons/bi';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import WSSellerAbstract from '../PurchaseScreen/WholeSalePrint/WSSellerAbstract.jsx';
import dayjs from 'dayjs';
import './WholeSaleAbstract.scss';
import { DatePicker } from 'antd';
const { RangePicker } = DatePicker;
const subDirectory = import.meta.env.BASE_URL;

const items = [
  {
    name: 'Home',
    link: `${subDirectory}app-page/home`,
  },
];

const WholeSaleSellerAbstract = () => {
  const dispatch = useDispatch();
  const formRef = useRef(null);

  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [TableData, setTableData] = useState([]);
  const [PrintData, setPrintData] = useState([]);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [OsearchedText, setOSearchedText] = useState('');
  const [OsearchedTextAmt, setOSearchedTextAmt] = useState('');
  const [EditRecord, setEditRecord] = useState({});
  const [EditRecordModal, setEditRecordModal] = useState(false);
  const [PaymentType, setPaymentType] = useState('P');
  const [OrderFromDate, setOrderFromDate] = useState();
  const [page, setpage] = useState(1);
  const [Rpage, setRpage] = useState(1);
  const [Opage, setOpage] = useState(1);
  const [orderModel, setOrderModel] = useState(false);
  const [OTableData, setOTableData] = useState([]);
  const [ORTableData, setORTableData] = useState([]);
  const [OFullData, setOFullData] = useState({});

  const itemsPerPage = 10;
  const indexOfLastItem = page * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = TableData?.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(TableData?.length / itemsPerPage);

  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');
  //   const UserType = getSession('UserType')

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchData();
  }, []);

  async function fetchData() {
    const data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
    };
    const gettingTableData = await dispatch(
      sellergetAbstractList(data)
    ).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      setTableData(gettingTableData?.data?.data);
    }
  }

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };
  useEffect(() => {
    if ([EditRecord]?.length > 0 && EditRecordModal) {
      if (EditRecord?.UniqueId) {
        const percentageAmt = EditRecord?.Amount ?? 0;
        formRef?.current?.setFieldsValue({ PercentageAmt: percentageAmt });
        let cmsAmt = 0;
        if (EditRecord?.AmountType === 'F') {
          cmsAmt = EditRecord?.Amount;
        } else if (EditRecord?.AmountType === 'P') {
          cmsAmt = (EditRecord?.OverallSales || 0) * (percentageAmt / 100);
        }
        formRef?.current?.setFieldsValue({
          CommissionAmt: cmsAmt > 0 ? cmsAmt : 0,
        });
      }
    }
  }, [EditRecord, EditRecordModal]);

  useEffect(() => {
    if (PrintData?.length > 0) {
      PrintFun();
    }
  }, [PrintData]);

  const onchangepaymentType = (value) => {
    formRef.current?.resetFields();
    formRef.current?.setFieldsValue({ PaymentType: value });
    setPaymentType(value);
  };

  const AmountChange = (e) => {
    const percentageAmt = e ?? 0;
    formRef.current?.setFieldsValue({ PercentageAmt: percentageAmt });
    let cmsAmt = 0;
    if (PaymentType === 'F') {
      cmsAmt = e;
    } else if (PaymentType === 'P') {
      cmsAmt = (EditRecord?.OverallSales || 0) * (percentageAmt / 100);
    }
    formRef.current?.setFieldsValue({ CommissionAmt: cmsAmt > 0 ? cmsAmt : 0 });
  };

  const vieworders = async (event) => {
    const TableData = event?.OrderDetails;
    const ORTableData = event?.ReceivedDetails;
    console.log('ORTableData', TableData, ORTableData);
    setOrderModel(true);
    setOTableData(TableData);
    setORTableData(ORTableData);
  };

  const OhandlePageChange = (current) => {
    setOpage(current);
  };

  const ORhandlePageChange = (current) => {
    setRpage(current);
  };

  const onOSearch = (value) => {
    setOSearchedText(value);
  };

  const onOSearchChange = (e) => {
    setOSearchedText(e?.target?.value);
  };
  const onOSearchAmt = (value) => {
    setOSearchedTextAmt(value);
  };

  const onOSearchChangeAmt = (e) => {
    setOSearchedTextAmt(e?.target?.value);
  };

  const printSet = () => {
    setPrintData(TableData);
  };

  const PrintFun = async () => {
    const WholeSaleStyle = `<style>
        
             @import url('https://fonts.googleapis.com/css2?family=Calistoga&display=swap');  
           @media print {
                     body { 
                         font-family:"Calistoga", serif; 
                         font-size: 13px; /* Adjust font size for print */
                         margin: 0;
                         padding: 0;
                     }
                 }    
        * {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.SalesBill-Master {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    background-color: #ffffff;
    font-family: "Calistoga", serif !important;

    p {
        font-family: "Calistoga", serif;
    }
}

.WSAbstract-header {
    display: flex;
    align-items: flex-start;
    gap: 4px;
    padding: 4px 4px;
}

.imagelogo {
    width: 50px;
    height: 60px;
}



.SBadd1 {
    font-size: 8px;
    font-weight: 600;
    width: 95%;
}

.SBadd2 {
    font-size: 8px;
    font-weight: 600;
    width: 95%;
}

.SBphone {
    font-size: 8px;
    font-weight: 600;
    width: 95%;
}

.infoOfMandi {
    width: 100%;
}

.WSAbstract-datetime {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 8px;
    width: 95%;
}

.WSAbstract-date {
    font-size: 10px;
    font-weight: 600;
    padding: 1px 0;
}

.WSAbstract-supName {
    font-size: 9px;
    font-weight: 600;
}

.WSAbstract-comTable {
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    padding: 0 8px;
    width: 99.5%;
}

.wstddata {
    // font-size: clamp(6px, 1vw, 16px) !important;
    font-size: 8px !important;
    font-weight: 400 !important;
    padding: 5px 1px !important;

}

.denominationTitle {
    font-size: 11px;
    font-weight: 600;
}

.cashierDiv {
    font-size: 11px;
    font-weight: 700;
    padding: 0 10px;
}

.thnkyouDiv {
    font-size: 12px;
    font-weight: 600;
    padding: 0 10px;
    width: 100%;
    text-align: center;
}

.inword {
    font-size: 7px;
    text-align: end;
    width: 95%;
    font-weight: 600;
    padding: 0 1rem;
}

.wc-header {
        display: flex;
        align-items: flex-start;
        gap: 4px;
        padding: 4px 4px;
    }
    
    .imagelogo {
        width: 65px;
        height: 60px;
    }
    
    .mandiName {
        font-size: 13px;
        font-weight: 700;
        width: 100%;
    }
    
    .wcadd1 {
        font-size: 10px;
        font-weight: 600;
        width: 95%;
    }
    
    .wcadd2 {
        font-size: 10px;
        font-weight: 600;
        width: 95%;
    }
    
    .wcphone {
        font-size: 8px;
        font-weight: 600;
        width: 95%;
    }
    
    .infoOfMandi {
        width: 100%;
        // text-align: center;
    }
    
    .wc-datetime {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 8px;
        width: 95%;
    }
    
    .wc-date {
        font-size: 11px;
        font-weight: 600;
        padding: 1px 0;
    }
    
    .wc-supName {
        font-size: 11px;
        font-weight: 600;
    }
    

.signatureofownerbill {
    font-size: 10px;
    text-align: end;
    width: 95%;
    font-weight: 600;
    padding: 2rem 1rem;
}
     .Add-Shortname{
        display: flex;
        width: 95%;
        justify-content: space-between;
        
    }
        .Address{
        display:flex;
        flex-direction:column;
        width:77%
        }
    .ShortNameDiv{
        display:flex;
        width:28%;
        font-size: 16px;
        font-weight: 700;
        background: #252525 !important;
        color:white;
        text-align:center;
        justify-content:center;
        align-items:center;
        margin:2px ;
        padding: 0px 5px;
        border: 1px solid black;
        border-radius:5px;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        }
    </style>`;

    await printDiv(`WSledger`, WholeSaleStyle);
    setPrintData([]);
  };
  const Ocolumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(Opage - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Sales No',
      key: 'OrderId',
      dataIndex: 'OrderId',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>
          {extractLastNumberOrderId(record?.OrderId, record?.FYStatus)}
        </a>
      ),
      filteredValue: [OsearchedText],
      onFilter: (value, record) => {
        return (
          String(extractLastNumberOrderId(record?.OrderId, record?.FYStatus))
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.productDetails?.map((item, index) => item.ProdName))
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
    },
    {
      title: 'Sales Date',
      key: 'SalesDate',
      dataIndex: 'SalesDate',
      render: (productDetails, record) => (
        <a style={{ color: 'black' }}>{dateFormatChange(record?.SalesDate)}</a>
      ),
    },

    {
      title: 'Product',
      key: 'ProdDetails',
      dataIndex: 'productDetails',
      render: (productDetails) =>
        productDetails?.length > 0
          ? productDetails.map((item, index) => (
              <div key={index}>{item.ProdName}</div>
            ))
          : 'No Products',
    },
    {
      title: 'Quality / UOM',
      key: 'ProdDetails',
      dataIndex: 'productDetails',
      render: (productDetails) =>
        productDetails?.length > 0
          ? productDetails.map((item, index) => (
              <div key={index}>{`${item.QualityName}- ${item.UomName}`}</div>
            ))
          : 'No Products',
    },
    {
      title: 'Received Qty',
      key: 'productDetails',
      dataIndex: 'productDetails',
      align: 'right',
      render: (productDetails) =>
        productDetails?.length > 0
          ? productDetails.map((item, index) => (
              <div key={index}>{item.SalesQty}</div>
            ))
          : 'No Recived Quantity',
    },
    {
      title: 'Total Amount',
      key: 'NetAmount',
      dataIndex: 'NetAmount',
      align: 'right',
      render: (productDetails, record) => (
        <a
          style={{ color: 'black' }}
          onClick={() => OnSelectPaidList(productDetails, record)}
        >
          {record?.NetAmount}
        </a>
      ),
    },
  ];

  const ORcolumns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '80px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(Rpage - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'No',
      key: 'UniqueId',
      dataIndex: 'UniqueId',
      render: (record) => <a style={{ color: 'black' }}>{record}</a>,
      filteredValue: [OsearchedTextAmt],
      onFilter: (value, record) => {
        return String(extractLastNumber(record?.UniqueId))
          ?.toLowerCase()
          ?.includes(value?.toLowerCase());
      },
    },
    {
      title: 'Date',
      key: 'Date',
      dataIndex: 'Date',
      render: (record) => (
        <a style={{ color: 'black' }}>{dateTimeFormatChange(record)}</a>
      ),
    },

    {
      title: 'Type',
      key: 'PaymentTypeName',
      dataIndex: 'PaymentTypeName',
      render: (record) => <a style={{ color: 'black' }}>{record}</a>,
    },

    {
      title: 'Amount',
      key: 'Amount',
      dataIndex: 'Amount',
      align: 'right',
      render: (record) => <a style={{ color: 'black' }}>{record}</a>,
    },
  ];

  const calculateBalance = (record) => {
    const openingBalance = record?.OpeningBalance || 0;
    const overallSales = record?.OverallSales || 0;
    const commissionAmount = record?.CommissionAmount || 0;
    const extraChargeAmount = record?.ExtraChargeAmount || 0;

    if (openingBalance >= 0) {
      return (
        Math.abs(openingBalance) -
        (overallSales - commissionAmount + extraChargeAmount)
      );
    } else {
      return (
        openingBalance - (overallSales - commissionAmount + extraChargeAmount)
      );
    }
  };
  const calculateFinalBalance = (record) => {
    const balance = calculateBalance(record);
    if (balance >= 0) {
      return balance - (record?.OverallReceivedAmount || 0);
    } else {
      return balance + (record?.OverallReceivedAmount || 0);
    }
  };
  const columns = [
    {
      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',
      dataIndex: 'SuppName',
      key: 'SuppName',
      width: '150px',
      align: 'left',
      render: (value, record) => (
        <a style={{ color: 'black', width: '200px' }}>
          {record.SuppName ? record.SuppName : record.SuppName}
        </a>
      ),
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return String(record.CustSuppName)
          ?.toLowerCase()
          ?.includes(value?.toLowerCase());
      },
      sorter: (a, b) => a?.CustSuppName?.length - b?.CustSuppName?.length,
      sortOrder:
        sortedInfo.columnKey === 'CustSuppName' ? sortedInfo.order : null,
      ellipsis: true,
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'OB',
      dataIndex: 'OpeningBalance',
      key: 'OpeningBalance',
      width: '80px',
      children: [
        {
          title: 'Balance',
          dataIndex: 'OpeningBalance',
          key: 'OpeningBalance',
          width: '90px',
          align: 'right',
          render: (text, record) => (
            <a style={{ color: 'red' }}>{text < 0 ? Math.abs(text) : 0}</a>
          ),
          onCell: (record) => ({
            onClick: () => {
              vieworders(record);
            },
          }),
        },
        {
          title: 'Advance',
          dataIndex: 'OpeningBalance',
          key: 'OpeningBalance',
          width: '90px',
          align: 'right',
          render: (text, record) => (
            <a style={{ color: 'green' }}>{text > 0 ? Math.abs(text) : 0}</a>
          ),
          onCell: (record) => ({
            onClick: () => {
              vieworders(record);
            },
          }),
        },
      ],
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },

    {
      title: 'Purchase',
      dataIndex: 'OverallSales',
      key: 'OverallSales',
      width: '100px',
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },

    // {
    //   title: "Commission",
    //   dataIndex: "CommissionAmount",
    //   key: "CommissionAmount",
    //   width: "110px",
    //   align:"right",
    //   render: (text, row) => (
    //     <div style={{
    //       color: '#1677ff',
    //       cursor: 'pointer',
    //       fontWeight: 'Bold'
    //     }}>
    //       {text}
    //     </div>
    //   ),
    //   onCell: (record) => ({
    //     onClick: () => {
    //       vieworders(record)
    //     },
    //   }),
    // },
    {
      title: 'Commission',
      dataIndex: 'ExtraChargeAmount',
      key: 'ExtraChargeAmount',
      width: '110px',
      align: 'right',
      render: (text, row) => (
        <div
          style={{
            color: '#1677ff',
            cursor: 'pointer',
            fontWeight: 'Bold',
          }}
        >
          {text}
        </div>
      ),
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'Total',
      dataIndex: 'Total',
      key: 'Total',
      width: '80px',
      align: 'right',
      render: (text, record) => (
        <a style={{ color: 'black' }}>
          {(record.OverallSales || 0) -
            (record.CommissionAmount || 0) +
            (record.ExtraChargeAmount || 0)}
        </a>
      ),
      filteredValue: filteredInfo.SuppPOC || null,
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'Grand Total',
      dataIndex: 'GrandTotal',
      key: 'GrandTotal',
      width: '100px',
      align: 'right',
      render: (text, record) => {
        const grandTotal = calculateBalance(record)?.toFixed(2);
        const color = grandTotal > 0 ? 'green' : 'red';
        return <a style={{ color }}>{Math.abs(grandTotal)}</a>;
      },
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'Given',
      dataIndex: 'OverallReceivedAmount',
      key: 'OverallReceivedAmount',
      width: '90px',
      align: 'right',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'Balance',
      dataIndex: 'Balance',
      key: 'Balance',
      width: '85px',
      align: 'right',
      render: (text, record) => {
        let finalBalance;
        const balance = calculateBalance(record);
        if (balance >= 0) {
          finalBalance = (
            balance - (record?.OverallReceivedAmount || 0)
          ).toFixed(2);
        } else {
          finalBalance = (
            balance + (record?.OverallReceivedAmount || 0)
          ).toFixed(2);
        }
        return (
          <a style={{ color: 'red' }}>
            {finalBalance < 0 ? Math.abs(finalBalance) : 0}
          </a>
        );
      },
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
    {
      title: 'Advance',
      dataIndex: 'Balance',
      key: 'Balance',
      align: 'right',
      render: (text, record) => {
        let finalAdvance;
        const balance = calculateBalance(record);
        if (balance >= 0) {
          finalAdvance = (
            balance - (record?.OverallReceivedAmount || 0)
          ).toFixed(2);
        } else {
          finalAdvance = (
            balance + (record?.OverallReceivedAmount || 0)
          ).toFixed(2);
        }
        return (
          <a style={{ color: 'green' }}>
            {finalAdvance > 0 ? Math.abs(finalAdvance) : 0}
          </a>
        );
      },
      onCell: (record) => ({
        onClick: () => {
          vieworders(record);
        },
      }),
    },
  ];

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const rangePresets = [
    {
      label: 'Last 7 Days',
      value: [dayjs().add(-7, 'd'), dayjs()],
    },
    {
      label: 'Last 14 Days',
      value: [dayjs().add(-14, 'd'), dayjs()],
    },
    {
      label: 'Last 30 Days',
      value: [dayjs().add(-30, 'd'), dayjs()],
    },
    {
      label: 'Last 90 Days',
      value: [dayjs().add(-90, 'd'), dayjs()],
    },
  ];

  const dateFormat = 'DD-MM-YYYY';

  const onRangeChange = async (dates, dateStrings) => {
    let fromDateVal = dateStrings[0]?.split('-');
    let toDateVal = dateStrings[1]?.split('-');
    if (dates) {
      let data = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        FromDate: fromDateVal[2] + '-' + fromDateVal[1] + '-' + fromDateVal[0],
        ToDate: toDateVal[2] + '-' + toDateVal[1] + '-' + toDateVal[0],
      };

      let gettingTableData = await dispatch(
        sellergetAbstractList(data)
      ).unwrap();
      if (gettingTableData?.data?.statusCode === 1) {
        setTableData(gettingTableData?.data?.data);
      } else {
        setTableData([]);
      }
    }
  };

  const disabledDate = (current) => {
    // Can not select days before today and today
    return current && current > dayjs().endOf('day');
  };
  return (
    <div className="WholeSaleAbstract">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />

        {orderModel && (
          <DefaultModal
            open={orderModel}
            footer={false}
            width={950}
            className={'orderDetailsModal-abstract'}
            children={
              <div className="kot-table">
                <div
                  className="modalSearchBar"
                  style={{ paddingBottom: '10px' }}
                >
                  <h3 className="kot-title">Order Details</h3>
                  <Search
                    placeholder="Search"
                    onSearch={onOSearch}
                    onSearchChange={onOSearchChange}
                  />
                </div>
                <div className="WholeSaleAbstract-Order">
                  <Tables
                    columns={Ocolumns}
                    dataSource={OTableData}
                    data={OTableData}
                    pagination={OhandlePageChange}
                  />
                </div>
                {ORTableData?.length > 0 && (
                  <>
                    <div className="WholeSaleAbstract-Order">
                      <div
                        className="modalSearchBar"
                        style={{ paddingBottom: '10px' }}
                      >
                        <div className="kot-title">Received</div>
                        <div>
                          <Search
                            placeholder="Search"
                            onSearch={onOSearchAmt}
                            onSearchChange={onOSearchChangeAmt}
                          />
                        </div>
                      </div>
                      <Tables
                        columns={ORcolumns}
                        dataSource={ORTableData}
                        data={ORTableData}
                        pagination={ORhandlePageChange}
                      />
                    </div>
                  </>
                )}
              </div>
            }
            handleCancel={() => {
              setOrderModel(false);
            }}
          />
        )}

        <div className="formAddNew">
          <div>
            <FormHeader title={'Abstract For Purchase'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>

            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div className="Dashboardrange">
                <RangePicker
                  presets={rangePresets}
                  onChange={onRangeChange}
                  format={dateFormat}
                  disabledDate={disabledDate}
                  inputReadOnly={true}
                />
              </div>

              <div>
                <BiSolidPrinter
                  className={
                    TableData?.length > 0
                      ? 'DateWiseReport-printerIcon'
                      : 'DateWiseReport-printerIcon-disabled'
                  }
                  onClick={() => {
                    printSet();
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <div className="reportTable">
          <Tables
            columns={columns}
            data={currentItems}
            dataSource={currentItems}
            // pagination={handlePageChange}
            onChange={handleChange}
            summary={(pageData) => {
              let totalOBBalanceAmount = pageData?.reduce((sum, item) => {
                return (
                  sum + (item.OpeningBalance < 0 ? item.OpeningBalance : 0)
                );
              }, 0);
              let totalOBAdvanceAmount = pageData?.reduce((sum, item) => {
                return (
                  sum + (item.OpeningBalance > 0 ? item.OpeningBalance : 0)
                );
              }, 0);
              let totalSalesAmount = pageData?.reduce(
                (sum, item) => sum + item.OverallSales,
                0
              );
              //   let totalCommissionAmount = pageData?.reduce((sum, item) => sum + (item.CommissionAmount || 0), 0);
              let totalExtraChargeAmount = pageData?.reduce(
                (sum, item) => sum + (item.ExtraChargeAmount || 0),
                0
              );
              let totalAmount = pageData?.reduce(
                (sum, item) =>
                  sum +
                  (item?.OverallSales -
                    (item?.CommissionAmount || 0) +
                    (item?.ExtraChargeAmount || 0)),
                0
              );
              let totalGrandTotalAmount = pageData?.reduce((sum, item) => {
                return sum + calculateBalance(item);
              }, 0);

              let totalRecivedAmount = pageData?.reduce((sum, item) => {
                const receivedAmount = item?.OverallReceivedAmount || 0;
                return sum + receivedAmount;
              }, 0);

              let totalBalanceAmount = pageData?.reduce((sum, item) => {
                const balance = calculateFinalBalance(item);
                return sum + (balance < 0 ? balance : 0);
              }, 0);

              let totalAdvanceAmount = pageData?.reduce((sum, item) => {
                const advance = calculateFinalBalance(item);
                return sum + (advance > 0 ? advance : 0);
              }, 0);
              return (
                <>
                  <Table.Summary.Row className="reportTable-totalSummary">
                    <Table.Summary.Cell index={0}></Table.Summary.Cell>
                    <Table.Summary.Cell index={1}>Total</Table.Summary.Cell>
                    <Table.Summary.Cell index={2} align="right">
                      {Math.abs(totalOBBalanceAmount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={3} align="right">
                      {totalOBAdvanceAmount}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={4} align="right">
                      {totalSalesAmount}
                    </Table.Summary.Cell>
                    {/* <Table.Summary.Cell index={5} align="right">{totalCommissionAmount?.toFixed(2)}</Table.Summary.Cell> */}
                    <Table.Summary.Cell index={6} align="right">
                      {totalExtraChargeAmount?.toFixed(2)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={7} align="right">
                      {totalAmount?.toFixed(2)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={8} align="right">
                      {Math.abs(totalGrandTotalAmount?.toFixed(2))}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={9} align="right">
                      {totalRecivedAmount}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={10} align="right">
                      {Math.abs(totalBalanceAmount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={11} align="right">
                      {totalAdvanceAmount}
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                </>
              );
            }}
          />{' '}
        </div>
        {totalPages > 1 && (
          <div
            className="paginationControls"
            style={{ justifyContent: 'flex-start' }}
          >
            {[...Array(totalPages)].map((_, pageIndex) => (
              <button
                key={pageIndex}
                onClick={() => handlePageChange(pageIndex + 1)}
              >
                {pageIndex + 1}
              </button>
            ))}
          </div>
        )}
      </div>

      <div style={{ display: 'none' }}>
        <WSSellerAbstract data={TableData} />
      </div>
    </div>
  );
};

export default WholeSaleSellerAbstract;
