import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Table ,Typography} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { SortOrder } from 'antd/lib/table/interface';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import form from 'antd/lib/form';
import { useForm } from 'antd/lib/form/Form';
import { UnitcodeService } from '../../../../../../shared-services/masters/src/lib/unit-code.services'
import { AgingReq, DutyDrawBackReportReq } from '@gtpl/shared-models/finance';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import moment from 'moment';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { Tabs } from 'antd';
const { TabPane } = Tabs;
import { CollectionsService } from '@gtpl/shared-services/finance';
const VendorWiseTaxDReport = () => {
  const CollectionService = new CollectionsService();
  const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const [unitId, setUnitId] = useState<number>(0);
   const [fromDate, setFromDate] = useState<string | undefined>(undefined);
    const [toDate, setToDate] = useState<string | undefined>(undefined);
  const { RangePicker } = DatePicker;
  const unitsService = new UnitcodeService()
  const { Option } = Select;
    const [reportRMData, setReportRMData] = useState([]);
      const [reportPMData, setReportPMData] = useState([]);
const [activeTab, setActiveTab] = useState("1");
  const [rmForm ] = useForm();
  const [pmForm ] = useForm()
    const [searchedColumn, setSearchedColumn] = useState('');
    const [searchText, setSearchText] = useState('');
    const [page, setPage] = React.useState(1);
    const searchInput = useRef(null);
    const { Text } = Typography;
  
  useEffect(() => {
    getVendorPackTaxData();
    getVendorRMTaxData();
    getAllPlants()
  }, []);
const getVendorPackTaxData = () => {
 const req=new AgingReq();
   if (pmForm.getFieldValue('invoiceDate')!= undefined) {
      req.fromDate = moment(pmForm.getFieldValue('invoiceDate')[0]).format('YYYY-MM-DD');
      req.toDate = moment(pmForm.getFieldValue('invoiceDate')[1]).format('YYYY-MM-DD');

    }
    if (pmForm.getFieldValue('unitId')!= undefined) {
      req.unitId = pmForm.getFieldValue('unitId');
    }
  CollectionService.getVendorPackTaxDataReport(req)
    .then(res => {
      if (res.status) {
           setReportPMData(res.data);
        } else {
          setReportPMData([]);
          AlertMessages.getErrorMessage("No data found");
            }
    })
    .catch(err => {
      setReportPMData([]);
      AlertMessages.getErrorMessage(err.message || "Failed to fetch data.");
    });
};
const getVendorRMTaxData = () => {
 const req=new AgingReq();
  if (rmForm.getFieldValue('invoiceDate')!= undefined) {
      req.fromDate = moment(rmForm.getFieldValue('invoiceDate')[0]).format('YYYY-MM-DD');
      req.toDate = moment(rmForm.getFieldValue('invoiceDate')[1]).format('YYYY-MM-DD');

    }
    if (rmForm.getFieldValue('unitId')!= undefined) {
      req.unitId = rmForm.getFieldValue('unitId');
    }
  CollectionService.getVendorRMTaxDataReport(req)
    .then(res => {
      if (res.status) {
          // const transformedData = transformVendorData(vendors);
          setReportRMData(res.data);
       
      } else {
        setReportRMData([]);
        AlertMessages.getErrorMessage("No data found");
      }
    })
    .catch(err => {
      setReportRMData([]);
      AlertMessages.getErrorMessage(err.message || "Failed to fetch data.");
    });
};
const transformVendorData = (vendors) => {
  const result = [];
  let sno = 1;

  vendors.forEach((vendor) => {
    const invoiceCount = vendor.invoices.length;

    vendor.invoices.forEach((invoice, index) => {
      result.push({
        sno: {
          text: sno,
          rowSpan: index === 0 ? invoiceCount : 0,
        },
        vendorName: {
          text: vendor.vendorName,
          rowSpan: index === 0 ? invoiceCount : 0,
        },
        unitName: invoice.unitName,
        company:invoice.company,
        invNo: invoice.invNo,
        invDate: invoice.invDate,
        totalAmount: invoice.totalAmount,
        taxPer: invoice.taxPer,
        tax: invoice.tax,
        balance: invoice.balance,
        agingBucket:invoice.agingBucket
        // Invoice-level aging buckets
        // r0_10: invoice.agingBuckets?.r0_10 || 0,
        // r11_20: invoice.agingBuckets?.r11_20 || 0,
        // r21_30: invoice.agingBuckets?.r21_30 || 0,
        // r31_40: invoice.agingBuckets?.r31_40 || 0,
        // r41_50: invoice.agingBuckets?.r41_50 || 0,
        // r51_60: invoice.agingBuckets?.r51_60 || 0,
        // r61_80: invoice.agingBuckets?.r61_80 || 0,
        // above_80: invoice.agingBuckets?.above_80 || 0,
      });
    });

    sno++;
  });

  return result;
};
const handleDateRange = (dates: any) => {
    if (dates && dates.length === 2) {
      setFromDate(dates[0].format('YYYY-MM-DD'));
      setToDate(dates[1].format('YYYY-MM-DD'));
    } else {
      setFromDate(undefined);
      setToDate(undefined);
    }
  };
  const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}


  const onReset = () => {
    rmForm.resetFields()
    pmForm.resetFields()
    setFromDate(undefined);
  setToDate(undefined);
  setUnitId(undefined);
    getVendorPackTaxData();
    getVendorRMTaxData();
  };
//   const handleUnit = (value: number) => {
//     setUnitId(value);
//     rmForm.setFieldsValue({ unitId: value }); 
//     pmForm.setFieldsValue({ unitId: value }); 
//   };
  const handleTabChange = (key) => {
  setActiveTab(key);

};
const exportBothTables = () => {
  const rmTable = document.getElementById('vendorRMTable');
  const pmTable = document.getElementById('vendorPMTable');
  if (!rmTable && !pmTable) return;
  const workbook = XLSX.utils.book_new();
  if (rmTable) {
    const ws1 = XLSX.utils.table_to_sheet(rmTable);
    XLSX.utils.book_append_sheet(workbook, ws1, 'Vendor RM Tax');
  }
  if (pmTable) {
    const ws2 = XLSX.utils.table_to_sheet(pmTable);
    XLSX.utils.book_append_sheet(workbook, ws2, 'Vendor PM Tax');
  }
  const excelBuffer = XLSX.write(workbook, {
    bookType: 'xlsx',
    type: 'array',
  });
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
  saveAs(blob, 'Vendor_Tax_Report.xlsx');
};
  const getColumnSearchProps = (dataIndex: string) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: visible => {
      if (visible) { setTimeout(() => searchInput.current.select()); }
    },
    render: text =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : text
      ) : null
  });
   function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
  };
const pmColumns:any[] =[ 
   {
        title: 'S No',
        key: 'sno',
        width: '70px',
        render: (text, record, index) => (page - 1) * 10 + (index + 1),
      },
      {title:'Vendor' ,
        dataIndex:'vendorName',
        sorter: (a, b) => a.vendorName.localeCompare(b.vendorName),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('vendorName'),
         render:(text)=> text || '-',
      },
        {title:'PAN Number' ,
        dataIndex:'panNumber',
        sorter: (a, b) => a.panNumber.localeCompare(b.panNumber),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('panNumber'),
         render:(text)=> text || '-',
      },
        {title:'Taxable Value' ,
        dataIndex:'taxableAmount',
        align:'right',
        sorter: (a, b) => a.taxableAmount.localeCompare(b.taxableAmount),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('taxableAmount'),
         render:(text)=> Number(text).toFixed(2) || '-',
      },
        {title:'TDS Section' ,
        align:'center',
        dataIndex:'vendorName',      
         render:(text)=> '194Q',
      },
        {title:'TDS Rate' ,
        align:'center',
        dataIndex:'vendorName',
        render:(text)=> '0.10%',
      },
        {title:'TDS Amount' ,
        align:'right',
        dataIndex:'tdsAmount',
        sorter: (a, b) => a.tdsAmount.localeCompare(b.tdsAmount),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('tdsAmount'),
         render:(text)=> Number(text).toFixed(2) || '-',
      },
]
const rmColumns:any[] =[ 
   {
        title: 'S No',
        key: 'sno',
        width: '70px',
        render: (text, record, index) => (page - 1) * 10 + (index + 1),
      },
      {title:'Farmer Name' ,
        dataIndex:'farmerName',
        sorter: (a, b) => a.farmerName.localeCompare(b.farmerName),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('farmerName'),
         render:(text)=> text || '-',
      },
        {title:'PAN Number' ,
        dataIndex:'panNumber',
         ...getColumnSearchProps('panNumber'),
         render:(text)=> text || '-',
      },
        {title:'Taxable Value' ,
          align:'right',
        dataIndex:'taxableAmount',
        sorter: (a, b) => a.taxableAmount.localeCompare(b.taxableAmount),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('taxableAmount'),
          render:(text)=> Number(text).toFixed(2) || '-',
      },
        {title:'TDS Section' ,
          align:'center',
        dataIndex:'vendorName',      
         render:(text)=> '194Q',
      },
        {title:'TDS Rate' ,
          align:'center',
        dataIndex:'vendorName',
        render:(text)=> '0.10%',
      },
        {title:'TDS Amount' ,
          align:'right',
        dataIndex:'tdsAmount',
        sorter: (a, b) => a.tdsAmount-(b.tdsAmount),
        sortDirections: ['descend', 'ascend'] as SortOrder[],
        ...getColumnSearchProps('tdsAmount'),
         render:(text)=> Number(text).toFixed(2) || '-',
      },
]

  return (
<div>
      <Card
        size="small"
        title={<span style={{ color: 'white' }}>Vendors  Tax Deducted Report</span>}
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
        extra={<>
                    <Button
  onClick={exportBothTables}
  style={{ border: 'none', padding: '8px 16px', borderRadius: '4px', cursor: 'pointer', marginRight: '30px' }}
>
  Get Excel
</Button>
                  </>}
      >
        <div className="card-container">
          <Tabs type={'card'} tabPosition={'top'} activeKey={activeTab} onChange={handleTabChange}>
            <TabPane
              key="1"
              tab={<span>{'RM'}</span>}
            >
              <Form form={rmForm} onFinish={getVendorRMTaxData}>
                <Row gutter={24}>
                  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                    <Form.Item
                      name="unitId"

                      label="Unit"
                      rules={[
                        {
                          required: false, message: 'Select Unit',
                        },
                      ]}
                    >
                      <Select
                        showSearch
                        optionFilterProp="children"
                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        placeholder="Select Unit"
                        allowClear
                        style={{ width: '100%' }}
                        // onChange={handleUnit}
                      >
                        {plantData.map(dropData => {
                          return <Option value={dropData.plantId}>{dropData.plantCode}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                  </Col>

                  <Col>
                    <Form.Item label="Invoice Date" name="invoiceDate">
                      <RangePicker onChange={handleDateRange} value={
      fromDate && toDate
        ? [moment(fromDate, 'YYYY-MM-DD'), moment(toDate, 'YYYY-MM-DD')]
        : null
    } />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item>
                      <Button
                        type="primary"
                        htmlType="submit"
                        style={{  width: "100%" }}
                      >
                        Search
                      </Button>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item>
                      <Button
                        danger
                        // icon={<UndoOutlined />}
                        onClick={onReset}
                        style={{ width: "100%" }}
                      >
                        Reset
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
 <div style={{ overflowX: 'auto' }}>
  {/* <table
  id='vendorRMTable'
  style={{
    width: '100%',
    borderCollapse: 'collapse',
    fontSize: '13px',
    border: '1px solid #ccc' 
  }}
>
    <thead style={{ backgroundColor: '#f0f0f0' }}>
      <tr>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>S No</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Farmer Name</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>PAN</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Taxable Value</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Section</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Rate</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Amount</th>



        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Unit</th> */}
        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice No</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice Date</th> */}
        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice Amount</th> */}
        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Tax Percentage</th> */}
        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Amount</th> */}
        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Due</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>0-10</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>10-20</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>20-30</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>30-40</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>40-50</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>50-60</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>60-80</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Above 80</th>
      </tr> 
    </thead>
    <tbody>
      {reportRMData.map((record, index) =>{ 
        console.log(record,'ppppppppp');
        
        return(
        <tr >
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{index+1}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.farmerName}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{re'taxableAmountord.panNumber:'-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.taxableAmount}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>194Q</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>0.10%</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{Number(record.tdsAmount).toFixed(2)}</td>

          {/* {record.sno?.rowSpan > 0 && (
            <td rowSpan={record.sno.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{index+1}</td>
          )}
          {/* {record.unitName?.rowSpan > 0 && (
            <td rowSpan={record.unitName.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.unitName.text}</td>
          )} 
          {record.vendorName?.rowSpan > 0 && (
            <td rowSpan={record.vendorName.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.vendorName.text}</td>
          )}
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.unitName}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.invNo}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.invDate ? moment(record.invDate).format('DD-MM-YYYY') : '-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{Number(record.totalAmount).toLocaleString() ?? '-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.taxPer ?? '-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.tax ?? '-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{Number(record.balance).toLocaleString() ?? '-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='0-10' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='10-20' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='20-30' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='30-40' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='40-50' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='50-60' ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=="60-80" ?Number(record.balance).toLocaleString(): 0}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='80+' ?Number(record.balance).toLocaleString(): 0}</td> 
        </tr>
      )})}
    </tbody>
  </table> */}
  <Table id='vendorRMTable'
  dataSource={reportRMData}
  columns={rmColumns}
  size='small'
    summary={(pageData) => {
          let totalTax = 0;
          // let totalExp = 0
          let totTds = 0
          
          pageData.forEach((e) => {
            console.log(e.total,'summaryyyyyyyyy');
            
            totalTax += Number(e.taxableAmount);
            totTds += Number(e.tdsAmount);
  
          });
  
          return (
 <>
              <Table.Summary.Row className='tableFooter' >
                <Table.Summary.Cell index={3} colSpan={3}><Text style={{ textAlign: 'end' }}>Total</Text></Table.Summary.Cell>
                <Table.Summary.Cell index={4}><Text style={{ textAlign: 'end' }}>{Number(totalTax).toLocaleString()}</Text></Table.Summary.Cell>
                <Table.Summary.Cell index={5}><Text style={{ textAlign: 'end' }}></Text></Table.Summary.Cell>
                <Table.Summary.Cell index={6}><Text style={{ textAlign: 'end' }}></Text></Table.Summary.Cell>
                <Table.Summary.Cell index={7}><Text style={{ textAlign: 'end' }}>{Number((totTds).toFixed(2)).toLocaleString()}</Text></Table.Summary.Cell>
              </Table.Summary.Row>
            </>
          );
        }
      }/>

</div>
             </TabPane>
            <TabPane
              key="2"
              tab={<span>{'Packing'}</span>}>
              <Form form={pmForm} onFinish={getVendorPackTaxData}>
                <Row gutter={24}>
                  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                    <Form.Item
                      name="unitId"

                      label="Unit"
                      rules={[
                        {
                          required: false, message: 'Select Unit',
                        },
                      ]}
                    >
                      <Select
                        showSearch
                        optionFilterProp="children"
                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        placeholder="Select Unit"
                        allowClear
                        style={{ width: '100%' }}
                        // onChange={handleUnit}
                      >
                        {plantData.map(dropData => {
                          return <Option value={dropData.plantId}>{dropData.plantCode}</Option>;
                        })}
                      </Select>
                    </Form.Item>
                  </Col>

                  <Col>
                    <Form.Item label="Invoice Date" name="invoiceDate">
                      <RangePicker onChange={handleDateRange} value={
      fromDate && toDate
        ? [moment(fromDate, 'YYYY-MM-DD'), moment(toDate, 'YYYY-MM-DD')]
        : null}
    />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item>
                      <Button
                        type="primary"
                        htmlType="submit"
                        style={{  width: "100%" }}
                      >
                        Search
                      </Button>
                    </Form.Item>
                  </Col>
                  <Col>
                    <Form.Item>
                      <Button
                        danger
                        // icon={<UndoOutlined />}
                        onClick={onReset}
                        style={{ width: "100%" }}
                      >
                        Reset
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>

             <div style={{ overflowX: 'auto' }}>
  {/* <table
  id='vendorPMTable'
  style={{
    width: '100%',
    borderCollapse: 'collapse',
    fontSize: '13px',
    border: '1px solid #ccc' 
  }}
>
    <thead style={{ backgroundColor: '#f0f0f0' }}>
      <tr>
         <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>S No</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Vendor</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>PAN</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Taxable Value</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Section</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Rate</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Amount</th>


        {/* <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>S No</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Vendor Name</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Unit</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice No</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice Date</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Invoice Amount</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Tax %</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>TDS Amount</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Due</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>0-10</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>10-20</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>20-30</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>30-40</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>40-50</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>50-60</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>60-80</th>
        <th style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>Above 80</th> 
      </tr>
    </thead>
    <tbody>
      {reportPMData.map((record, index) => (
        // <tr key={`${record.vendorName?.text}-${record.invNo}-${record.unitName}-${index}`}>
        //   {record.sno?.rowSpan > 0 && (
        //     <td rowSpan={record.sno.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{index+1}</td>
        //   )}
        //   {/* {record.unitName?.rowSpan > 0 && (
        //     <td rowSpan={record.unitName.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.unitName.text}</td>
        //   )} 
        //   {record.vendorName?.rowSpan > 0 && (
        //     <td rowSpan={record.vendorName.rowSpan} style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.vendorName.text}</td>
        //   )}
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.unitName}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.invNo}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.invDate ? moment(record.invDate).format('DD-MM-YYYY') : '-'}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.totalAmount ?? '-'}</td>
        //   {/* <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.taxPer ?? '-'}</td> 
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.tax ?? '-'}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{Number(record.balance).toLocaleString() ?? '-'}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='0-10' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='10-20' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='20-30' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='30-40' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='40-50' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='50-60' ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=="60-80" ?Number(record.balance).toLocaleString(): 0}</td>
        //   <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.agingBucket=='80+' ?Number(record.balance).toLocaleString(): 0}</td>
       <tr >
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{index+1}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.vendorName}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.panNumber?record.panNumber:'-'}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{record.taxableAmount}</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>194Q</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>0.10%</td>
          <td style={{ border: '1px solid #ccc', padding: '6px', textAlign: 'center'}}>{Number(record.tdsAmount).toFixed(2)}</td>

        </tr>
      ))}
    </tbody>
  </table> */}
    <Table id='vendorPMTable'
  dataSource={reportPMData}
  columns={pmColumns}
  size='small'
  summary={(pageData) => {
          let totalTax = 0;
          // let totalExp = 0
          let totTds = 0
          
          pageData.forEach((e) => {
            console.log(e.total,'summaryyyyyyyyy');
            
            totalTax += Number(e.taxableAmount);
            totTds += Number(e.tdsAmount);
  
          });
  
          return (
            <>
              <Table.Summary.Row className='tableFooter' >
                <Table.Summary.Cell index={3} colSpan={3}><Text style={{ textAlign: 'end' }}>Total</Text></Table.Summary.Cell>
                <Table.Summary.Cell index={4}><Text style={{ textAlign: 'end' }}>{Number(totalTax).toLocaleString()}</Text></Table.Summary.Cell>
                <Table.Summary.Cell index={5}><Text style={{ textAlign: 'end' }}></Text></Table.Summary.Cell>
                <Table.Summary.Cell index={6}><Text style={{ textAlign: 'end' }}></Text></Table.Summary.Cell>
                <Table.Summary.Cell index={7}><Text style={{ textAlign: 'end' }}>{Number((totTds).toFixed(2)).toLocaleString()}</Text></Table.Summary.Cell>
              </Table.Summary.Row>
            </>
          );
        }
      }/>
         
</div>

            </TabPane></Tabs></div>
      </Card>
    </div>
  );
};


export default VendorWiseTaxDReport;
