import { Button, Card, Input, Row, Form, Col, DatePicker, Select } from 'antd';
const { Option } = Select;
import Table, { ColumnProps, ColumnType } from 'antd/lib/table';
import React, { useEffect, useState } from 'react'
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import { CollectionsService } from '@gtpl/shared-services/finance';
import * as XLSX from 'xlsx';
import { FilterDropdownProps } from 'antd/lib/table/interface';
import { useForm } from 'antd/lib/form/Form';
import { Excel } from 'antd-table-saveas-excel';
import { DutyDrawBackReportReq, RodtepReportReq } from '@gtpl/shared-models/finance';

const DutyDrawBackReport = () => {
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
      });
   const CollectionService = new CollectionsService();
   const [getAllData, setGetAllData] = useState<any[]>([])
   const [allInvoiceNumber, setAllInvoiceNumber] = useState<any[]>([])
   const [form] = useForm();
   const { RangePicker } = DatePicker;

useEffect(()=>{
    getDutyDrawBackReport();
    getAllInvoiceNumber();
},[])

   const getDutyDrawBackReport =()=>{
    const req =new DutyDrawBackReportReq()
        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')
    }
    if (form.getFieldValue('invoiceNumber') !== undefined) {
      req.invoiceNumber = form.getFieldValue('invoiceNumber')
    }
    CollectionService.getDutyDrawBackReport(req).then((res)=>{
        if(res){
            setGetAllData(res.data)
        }
    })
   }

   const getAllInvoiceNumber =()=>{
    CollectionService.getAllInvoiceNumber().then((res)=>{
        if(res){
            setAllInvoiceNumber(res.data)
        }
    })
   }

   const onReset = () => {
    form.resetFields();
    setGetAllData([]);
    getDutyDrawBackReport();
  };


  const exportedData = [];
  const execlData = getAllData
  let x = 1;
  const data = [
    { title: 'S No', dataIndex: 'sNo', width: 70, render: (text, object, index) => { return x++; } },
    { title: 'Invoice Number', dataIndex: 'invoiceNumber', width: 150, render: (text, record) => { return record.invoiceNumber ? record.invoiceNumber : '-' } },
    { title: 'Invoice Date', dataIndex: 'invoiceDate', width: 100,  render: (text: string) => {
            if (!text) return '-';
        
            return moment(text).format('DD-MM-YYYY');
        }, },
    { title: 'Shipping Bill No', dataIndex: 'shippingBillNo', width: 150, render: (text, record) => { return record.shippingBillNo || '-' } },
    { title: 'Shipping Bill Date', dataIndex: 'shippingBillDate', width: 150,  render: (text: string) => {
            if (!text) return '-';
        
            return moment(text).format('DD-MM-YYYY');
        }, },
    { title: 'Party Name', dataIndex: 'partyName', width: 250, render: (text, record) => { return record.partyName || '-' } },
    { title: 'FOB Value', dataIndex: 'fobValueInr', width: 120, render: (text, record) => { return record.fobValueInr || '-' } },
    { title: 'Balance Duty Draw Back Receivable', dataIndex: 'balanceDutyDrawBack', width: 120, render: (text, record) => { return record.balanceDutyDrawBack || '-' } },
    { title: 'Aging', dataIndex: 'lotNumber', width: 100, render: (text, record) => { return record.invoiceDate ? moment().diff(moment(record.invoiceDate, 'YYYY-MM-DD'), 'days') : '-' } },

];


const exportExcel = () => {
  const excel = new Excel();

  let totalFobValue = 0;
  let totalBalanceDutyDrawBack = 0;

  const processedData = getAllData.map((record) => {
    const fobValue = parseFloat(record.fobValueInr) || 0;
    const balanceDutyDrawBack = parseFloat(record.balanceDutyDrawBack) || 0;

    totalFobValue += fobValue;
    totalBalanceDutyDrawBack += balanceDutyDrawBack;

    return {
      ...record,
     invoiceDate: record.invoiceDate,
        shippingBillDate: record.shippingBillDate,
      aging: record.invoiceDate ? moment().diff(moment(record.invoiceDate, 'YYYY-MM-DD'), 'days') : '-',
      fobValueInr: fobValue.toFixed(2).toString(), 
      balanceDutyDrawBack: balanceDutyDrawBack.toFixed(2).toString(),
    };
  });

  processedData.push({
    sNo: '', 
    invoiceNumber: '',
    invoiceDate: '',
    shippingBillNo: '',
    shippingBillDate: '',
    partyName:'Total',
    fobValueInr: totalFobValue.toFixed(2).toString(), 
    balanceDutyDrawBack: totalBalanceDutyDrawBack.toFixed(2).toString(), 
    aging: '',
  });

  excel
    .addSheet('Duty-Drawback-Report')
    .addColumns(data)
    .addDataSource(processedData, { str2num: true })
    .saveAs('Duty-Drawback-Report.xlsx');
};

   

const getColumnSearchProps = (dataIndex: string): ColumnType<any> => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: FilterDropdownProps) => (
        <div style={{ padding: 8 }}>
            <Input
                placeholder={`Search ${dataIndex}`}
                value={selectedKeys[0]}
                onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                onPressEnter={() => confirm()}
                style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <Button type="primary" onClick={() => confirm()} icon={<SearchOutlined />} size="small" style={{ width: 90, marginRight: 8 }}>
                Search
            </Button>
            <Button onClick={() => clearFilters?.()} size="small" style={{ width: 90 }}>
                Reset
            </Button>
        </div>
    ),
    filterIcon: (filtered: boolean) => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />,
    onFilter: (value, record) => record[dataIndex]?.toString().toLowerCase().includes(value.toString().toLowerCase()),
});

   const columns: any[] = [
    {
        title: 'S No',
        dataIndex: 'sNo',
        render: (text, object, index) => {
          const page = pagination.current || 1;
          const pageSize = pagination.pageSize || 10;
      
          return (page - 1) * pageSize + (index + 1);
        },
        width: 60,
    },
      
    {
       title: 'Invoice Number', 
      width: 200,
      dataIndex: 'invoiceNumber',

        render: (text: any, record: any) => { return record.invoiceNumber ? record.invoiceNumber : '-' } ,
        sorter: (a, b) => a.invoiceNumber.localeCompare(b.invoiceNumber),
      sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceNumber')
    },
    {
        title: 'Invoice Date',
        key: 'invoiceDate',
        dataIndex: 'invoiceDate',
        width: '180px',
            
    },
     
    {
       title: 'Shipping Bill No', 
      width: 200,
      dataIndex: 'shippingBillNo',
      ...getColumnSearchProps('shippingBillNo')
     },
     {
      title: 'Shipping Bill Date', 
     width: 200,
     dataIndex: 'shippingBillDate',
    },
    {
       title: 'Party Name', 
       width: 200,
       dataIndex: 'partyName',
        //  render: (text: any, record: any) => { return record.eta ? moment(record.eta).format('DD-MM-YYYY') : '-' },
      //    sorter: (a, b) => a.eta.localeCompare(b.eta),
      //  sortDirections: ['descend', 'ascend'],
     },
     {
        title: 'FOB VALUE', 
       width: 100,
       dataIndex: 'fobValueInr',
       render: (text: any) => 
        text !== undefined && text !== null ? Number(Number(text).toFixed(2)).toLocaleString() : '-',
    sorter: (a, b) => parseFloat(a?.fobValueInr || 0) - parseFloat(b?.fobValueInr || 0),
    sortDirections: ['descend', 'ascend'],
      },
    //   {
    //     title: 'DutyDrawBack', 
    //    width: 200,
    //    dataIndex: 'dutyDrawBack',
    //   },
    {  
        title: 'Balance DutyDrawBack Receivable',
        width: 200,
        dataIndex: 'balanceDutyDrawBack',
        render: (text: any) => 
            text !== undefined && text !== null ? Number(Number(text).toFixed(2)).toLocaleString() : '-',
        sorter: (a, b) => parseFloat(a?.balanceDutyDrawBack || 0) - parseFloat(b?.balanceDutyDrawBack || 0),
        sortDirections: ['descend', 'ascend'],
    },
    
     {
        title: 'Aging',
        key:'aging',
        render:(text,record)=>{
        if (!record.invoiceDate) return '-';

        const invoiceDate = moment(record.invoiceDate, 'YYYY-MM-DD');
        if (!invoiceDate.isValid()) return 'Invalid Date';

        const today = moment();
        const agingDays = today.diff(invoiceDate, 'days');
        let color = 'green';
        if(agingDays > 30 ) color = 'red';
        else if(agingDays >15) color = 'orange'

        return (
            <span style={{color, fontWeight: 'bold' }}>
            {agingDays}
            </span>
        );
        },
     },
    ];

    return (
        <div>
          <Card
            title={<span style={{ color: 'white' }}>Duty Draw Back 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 layout='vertical' form={form}>
                <Row gutter={16} align="middle">
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 10 }} lg={{ span: 8 }} xl={{ span: 6 }}>
                    <Form.Item
                    name="date"
                    label="Shipping Bill Date"
                    rules={[
                        {
                        required: false,
                        message: "Select date range"
                        },
                    ]}
                    >
                    <RangePicker  />
                    </Form.Item>
                </Col>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="invoiceNumber" label="Invoice Number" >
             
                   
                            <Select
                                placeholder="Select invoiceNumber"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                allowClear

                            >
                                {allInvoiceNumber.map(dropData => {
                                    return <Option value={dropData.invoiceNumber}>{dropData.invoiceNumber}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                <Col style={{ paddingLeft: '10px', marginTop: '7px' }}>
                    <Button 
                    type="primary" 
                    
                    //   disabled={disable} 
                    onClick={() => getDutyDrawBackReport()}
                    >
                    Get Report
                    </Button>
                </Col>
                <Col style={{ paddingLeft: '10px', marginTop: '7px' }}>
                    <Button 
                    
                    type="primary" 
                    
                    onClick={onReset}
                    > 
                    Reset 
                    </Button>
                </Col>
                </Row>
            </Form>
          </Card>
          <Table
            columns={columns}
            dataSource={getAllData}
            scroll={{ x: true }}
            pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                onChange: (page, pageSize) => setPagination({ current: page, pageSize }),}}
            bordered
            summary={(pageData) => {
              let totalFob = 0;
              let totalBalance = 0;
            
              pageData.forEach(({ fobValueInr,balanceDutyDrawBack }) => {
                  totalFob += parseFloat(fobValueInr) || 0;
                  totalBalance += parseFloat(balanceDutyDrawBack) || 0;
                });
            
              return (
                <Table.Summary.Row>
                  <Table.Summary.Cell index={5} colSpan={6}>
                    Total
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={6}>
                    {Number(totalFob.toFixed(2)).toLocaleString()}
                  </Table.Summary.Cell>


                  <Table.Summary.Cell index={7}>
                    {Number(totalBalance.toFixed(2)).toLocaleString()}
                  </Table.Summary.Cell>
                </Table.Summary.Row>
              );
            }}
          />
        </div>
      );
}

export default DutyDrawBackReport