import React, { useEffect, useRef, useState } from 'react';
import {Button, Card, Col, DatePicker, Form, Input,  Row,  Select, Table, Typography} from 'antd'
import {FormOutlined, SearchOutlined ,DownloadOutlined} from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import './pages-reports-reports-components-export-receivables-report.css';
import {CollectionsService} from '@gtpl/shared-services/finance'
import search from 'antd/lib/transfer/search';
import { useForm } from 'antd/lib/form/Form';
import moment from 'moment';
import { ReceivablesSummaryReq } from '@gtpl/shared-models/finance';
import { Excel } from 'antd-table-saveas-excel';

/* eslint-disable-next-line */
export interface ReceivablesSummaryReportProps {}

export function ReceivablesSummaryReport(
  props: ReceivablesSummaryReportProps
) {
  const [data, setData] = useState([])
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const searchInput = useRef(null);
  const [isModalVisible,setIsModalVisible] = useState<boolean>(false)
  const [acceptButton,setAcceptButton] = useState<boolean>(false)
  const [collapse,SetCollapse] = useState<boolean>(false)
  const[form] = useForm()
  const { Option } = Select;
  const service = new CollectionsService()
  const { RangePicker } = DatePicker;
  const { Text } = Typography;


  useEffect(() => {
    getData()
}, [])
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };

  const getData = () => {
    const req =new ReceivablesSummaryReq()
    if(form.getFieldValue('date')!= undefined){
  req.fromDate = moment(form.getFieldValue('date')[0]).format('YYYY-MM-DD')
  req.toDate = moment(form.getFieldValue('date')[1]).format('YYYY-MM-DD')
}
    service.getReceivablesSummaryReport(req).then((res)=>{
      if(res.status){
      setData(res.data)
      }else{
        setData([])
      }
    })
}
const search =() =>{
  getData()
}
  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
          size="small"
          style={{ width: 90 }}
          onClick={() => {
            handleReset(clearFilters);
            setSearchedColumn(dataIndex);
            confirm({ closeDropdown: true });
          }}
        >
          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,
  });
  const onReset = () => {
    form.resetFields();
    getData();
  };
  const columns: any[] = [
    {
      title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
        if (index == data.length) {
          return null;
        } else {
          return index + 1
        }
      },
      width: 60,

    },
    {
      title: 'Country', 
     width: 200,
     dataIndex: 'country',
       render: (text: any, record: any) => { return record.country? record.country : '-' },
       sorter: (a, b) => a.country.localeCompare(b.country),
     sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('country')
    },
    {
      title: 'BMR Industries', 
     width: 200,
     dataIndex: 'bmrAmt',
     align:'right',
       render: (text: any, record: any) => { return record.bmrAmt? Number(record.bmrAmt).toLocaleString() : '-' },
       sorter: (a, b) => a.bmrAmt-b.bmrAmt,
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'BMR Exports', 
     width: 200,
     dataIndex: 'otherAmt',
     align:'right',
            render: (text: any, record: any) => { return record.otherAmt? Number(record.otherAmt).toLocaleString() : '-' },
       sorter: (a, b) => a.otherAmt-b.otherAmt,
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Total', 
     width: 200,
     dataIndex: 'total',
     align:'right',
       render: (text: any, record: any) => { return record.total? Number(record.total).toLocaleString() : '-' },
       sorter: (a, b) => a.total-b.total,
     sortDirections: ['descend', 'ascend'],
    },
  ]
  const exportExcel = () => {
    const excel = new Excel();
    excel
      .addSheet('receivables-summary-report')
      .addColumns(columns)
      .addDataSource(data, { str2num: true })
      .saveAs('receivables-summary.xlsx');
  }
  return (
    <Card size="small" title={<span style={{ color: 'white' }} > Receivables Summary Report</span>}
    extra={
      <div>
        <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{marginRight:30}}>
          Get Excel
        </Button></div>}
    style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <Form form={form} onFinish={search} layout='vertical'>
            <Row gutter={24}>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 10 }} lg={{ span: 8 }} xl={{ span: 6 }}>

                <Form.Item label='Date' name='date' >
                 <RangePicker/>
                </Form.Item>
              </Col>
              <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
                <Form.Item>
                  <Button type='primary' htmlType='submit'>Get Report</Button>
                </Form.Item></Col>
                <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
                <Form.Item>
                  <Button type='primary' onClick={onReset}>Reset</Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
     {data.length>0?(
      <Table size='small' columns={columns} dataSource={data}
      bordered
      summary={(pageData) => {
        let totalInd = 0;
        let totalExp = 0
        let totAmt = 0
        console.log(pageData,'oooooooooo');
        
        pageData.forEach((e) => {
          console.log(e.total,'summaryyyyyyyyy');
          
          totalInd += Number(e.bmrAmt);
          totalExp += Number(e.otherAmt);
          totAmt += Number(e.total);

        });

        return (
          <>
            <Table.Summary.Row className='tableFooter' >
              <Table.Summary.Cell index={1} ><Text ></Text></Table.Summary.Cell>
              <Table.Summary.Cell index={2}><Text style={{ textAlign: 'end' }}>Total</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={3}><Text style={{ textAlign: 'end' }}>{Number(totalInd).toLocaleString()}</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={4}><Text style={{ textAlign: 'end' }}>{Number(totalExp).toLocaleString()}</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={3}><Text style={{ textAlign: 'end' }}>{Number(totAmt).toLocaleString()}</Text></Table.Summary.Cell>
            </Table.Summary.Row>
          </>
        );
      }
      }/>
     ):'No Data Found'}
    </Card>
  );
}

export default ReceivablesSummaryReport;
