import { Button, Card, Col, DatePicker, Form, Input, Row, Select } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { CollectionsService } from 'libs/shared-services/finance/src/lib/collections-service';
import { Excel } from 'antd-table-saveas-excel';
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { IgstCollectionsReq, IgstReportReq, PaymentTypeReq } from '@gtpl/shared-models/finance';
import { useForm } from 'antd/lib/form/Form';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from 'libs/shared-services/masters/src/lib/unit-code.services';

const IGSTAgingReport = () => {
  const [searchText, setSearchText] = useState('');
  const searchInput = useRef(null);
  const [searchedColumn, setSearchedColumn] = useState('');
const [page, setPage] = React.useState(1);
  const [pageSize, setPageSize] = useState(100);
  const CollectionService = new CollectionsService();
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState<ColumnProps<any>[]>([]);
   const [allInvoiceNumber, setAllInvoiceNumber] = useState<any[]>([])
   const [form] = useForm();
   const { Option } = Select;
     const [years,setYears] = useState<any[]>([])
  const saleService = new SaleOrderService();
  const service = new CollectionsService()
  const [buyers, setBuyers] = useState([])
const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const unitsService = new UnitcodeService();
  const [unitId, setUnitId] = useState<number>(0);
 
   const { RangePicker } = DatePicker;
  useEffect(() => {
    getIGSTAgingReport()
    getAllInvoiceNumber()
    getAllFinancialYear()
    getBuyers();
    getAllPlants()
}, []);
const getIGSTAgingReport = () => {
  const dateRange = form.getFieldValue('date');
  const fromDate = dateRange ? moment(dateRange[0]).format('DD-MM-YYYY') : '';
  const toDate = dateRange ? moment(dateRange[1]).format('DD-MM-YYYY') : '';

  const req = new IgstReportReq(
    form.getFieldValue('invoiceNumber') || '',
    form.getFieldValue('unitId') || 0,
    form.getFieldValue('buyer') || 0,
    form.getFieldValue('financialYear') || '',
    fromDate,
    toDate
  );

  CollectionService.getIGSTAgingReport(req)
    .then(res => {
      if (res.status) {
        if (res.data && res.data.length > 0) {
          setData(res.data);
          AlertMessages.getSuccessMessage('Data retrieved successfully.');
        } else {
          setData([]);
          AlertMessages.getInfoMessage('No data found for the selected filters.');
        }
      } else {
        setData([]);
        AlertMessages.getErrorMessage(res.internalMessage || 'Something went wrong.');
      }
    })
    .catch(err => {
      setData([]);
      AlertMessages.getErrorMessage(err.message || 'Server error occurred.');
    });
};

  const getAllInvoiceNumber =()=>{
    CollectionService.getAllInvoiceNumber().then((res)=>{
        if(res){
            setAllInvoiceNumber(res.data)
        }
    })
   }
   const getAllFinancialYear  = () => {
    saleService.getAllFinancialYear().then(res => {
      if (res.status) {
        setYears(res.data);
      } else {
        if (res.intlCode) {
          setYears([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setYears([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }
  const getBuyers = () => {
    service.getBuyers(undefined).then((res)=>{
      if(res.status){
      setBuyers(res.data)
      }
    })
  }
  const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}
  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (dataIndex) => ({
    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
  });

const handleDownload = () => {
  const excel = new Excel();
  const formattedData = data.map((item, index) => {
    const shippingDate = moment(item.shippingBillDate);
    return {
      sno: index + 1,
      poNumber: item.poNumber,
      invNumber: item.invNumber,
      invDate: item.invDate,
      shipingBillNo: item.shipingBillNo,
      shippingBillDate: item.shippingBillDate ? moment(item.shippingBillDate).format('DD-MM-YYYY') : '',
      endCustomer: item.endCustomer,
      invAMT: item.invAMT,
      exchangeRate: item.exchangeRate,
      invoiceINR: item.invAMT && item.exchangeRate ? (parseFloat(item.invAMT) * parseFloat(item.exchangeRate)).toFixed(2) : '-',
      igstAmount: item.igstAmount,
      aging: shippingDate.isValid() ? moment().diff(shippingDate, 'days') : '-',
    };
  });

  excel
    .addSheet("IGST Aging Report")
    .addColumns([
      { title: 'S No', dataIndex: 'sno' },
      { title: 'PO Number', dataIndex: 'poNumber' },
      { title: 'Invoice Number', dataIndex: 'invNumber' },
      { title: 'Invoice Date', dataIndex: 'invDate' },
      { title: 'Shipping Bill No', dataIndex: 'shipingBillNo' },
      { title: 'Shipping Bill Date', dataIndex: 'shippingBillDate' },
      { title: 'Party Name', dataIndex: 'endCustomer' },
      { title: 'Invoice Amount in USD', dataIndex: 'invAMT' },
      { title: 'Exchange Rate', dataIndex: 'exchangeRate' },
      { title: 'Invoice in INR', dataIndex: 'invoiceINR' },
      { title: 'IGST Receivable', dataIndex: 'igstAmount' },
      { title: 'Aging (Days)', dataIndex: 'aging' },
    ])
    .addDataSource(formattedData)
    .saveAs("IGST-Aging-Report.xlsx");
};


const columnsSkelton: ColumnProps<any>[] = [
  {
            title: 'S No',
            key: 'sno',
            width: 70,
            render: (text, object, index) => (page - 1) * pageSize + (index + 1),
     },
  {
    title: 'unit',
    dataIndex: 'company',
    sorter: (a, b) => a.company.localeCompare(b.company),
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('company'),
  },
  {
    title: 'PO Number',
    dataIndex: 'poNumber',
    sorter: (a, b) => a.poNumber.localeCompare(b.poNumber),
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('poNumber'),
  },
  {
    title: 'Invoice Number',
    dataIndex: 'invNumber',
    sorter: (a, b) => a.invNumber.localeCompare(b.invNumber),
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('invNumber'),
  },
  {
  title: 'Invoice Date',
  dataIndex: 'invDate',
  sorter: (a, b) => a.invDate.localeCompare(b.invDate),
  sortDirections: ['descend', 'ascend'],
},
  {
    title: 'Shipping Bill No',
    dataIndex: 'shipingBillNo',
   ...getColumnSearchProps('shipingBillNo'),
  },
  {
    title: 'Shipping Bill Date',
    dataIndex: 'shippingBillDate',
    sorter: (a, b) => a.shippingBillDate?.localeCompare(b.shippingBillDate),
  sortDirections: ['descend', 'ascend'],
    render: (shippingBillDate) => shippingBillDate ? moment(shippingBillDate).format('DD-MM-YYYY') : '',

  },

  {
    title: 'Party Name',
    dataIndex: 'endCustomer',
    sorter: (a, b) => a.endCustomer.localeCompare(b.endCustomer),
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('endCustomer'),

  },
  {
    title: 'Invoice Amount in USD',
    dataIndex: 'invAMT',
    align: 'right',
    sorter: (a, b) => a.invAMT - b.invAMT,
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('invAMT'),
      render: (_, record) => {
    return isNaN(record?.invAMT) ? '-' : (record?.invAMT)?.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  },
  },
  {
    title: 'Exchange Rate',
    dataIndex: 'exchangeRate',
    align: 'right',
    sorter: (a, b) => a.exchangeRate - b.exchangeRate,
    sortDirections: ['descend', 'ascend'],
    ...getColumnSearchProps('exchangeRate'),
  },
  {
  title: 'Invoice in INR',
  key: 'invoiceINR',
  align: 'right',
  render: (_, record) => {
    const amt = parseFloat(record.invAMT);
    const rate = parseFloat(record.exchangeRate);
    const total = amt * rate;
    return isNaN(total) ? '-' : total.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  },
  sorter: (a, b) =>
    (parseFloat(a.invAMT) * parseFloat(a.exchangeRate)) -
    (parseFloat(b.invAMT) * parseFloat(b.exchangeRate)),
  sortDirections: ['descend', 'ascend'],
},
{
  title: 'IGST Receivable',
  dataIndex: 'igstAmount',
  align: 'right',
  sorter: (a, b) => a.igstAmount - b.igstAmount,
  sortDirections: ['descend', 'ascend'],
  ...getColumnSearchProps('igstAmount'),
  render: (igstAmount) =>
    igstAmount != null
      ? parseFloat(igstAmount).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : '-',
}
,
  {
    title: 'Aging (Days)',
    key: 'aging',
    align: 'right',
    render: (_, record) => {
      const shippingDate = moment(record.shippingBillDate);
     const aging = shippingDate.isValid() ? moment().diff(shippingDate, 'days') : '-';
    return <span style={{ color: 'red' }}>{aging}</span>;
    },
    sorter: (a, b) =>
      moment().diff(moment(a.shippingBillDate), 'days') -
      moment().diff(moment(b.shippingBillDate), 'days'),
    sortDirections: ['descend', 'ascend'],
  },
];
const handleUnit = (value) => {
  setUnitId(value)
}
const onReset = () => {
    form.resetFields();
   getIGSTAgingReport()
  };
  return (
    <div>
      <Card
        title={<span style={{ color: 'white' }}>IGST Receivable Aging Report</span>}
        extra={
          <div>
            <Button icon={<DownloadOutlined />} onClick={handleDownload} 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 span={4}>
        <Form.Item name="unitId"   label="Unit" rules={[{ required: false,message: 'Missing 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.company}</Option>
                    })}
                </Select>
            </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 xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                                                  <Form.Item name="financialYear" label="Financial Year">
                                                    <Select
                                                      showSearch
                                                      placeholder="Select Financial Year"
                                                      optionFilterProp="children"
                                                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                      allowClear
                                                    >
                                                      {years.filter(year => year.financialYear !== null).map((y: any) => (
                                                        <Select.Option key={y.financialYear} value={y.financialYear}>
                                                          {y.financialYear}
                                                        </Select.Option>
                                                      ))}
                                                    </Select>
                                                  </Form.Item>
                                                </Col>
                  <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                  
                                                <Form.Item label='Party Name' name='buyer'>
                                                    <Select
                                                        placeholder="Select buyer"
                                                        allowClear
                                                        showSearch
                                                        optionFilterProp="children"
                                                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                        
                                                    >
                  
                                                        {buyers.map(dropData => {
                                                            return <Option value={dropData.buyerId}>{dropData.buyer}</Option>;
                                                        })}
                  
                                                    </Select>
                  
                                                </Form.Item>
                                            </Col>
                <Col style={{ paddingLeft: '10px', marginTop: '7px' }}>
                    <Button 
                    type="primary" 
                    //   disabled={disable} 
                    onClick={() => getIGSTAgingReport()}
                    >
                    Get Report
                    </Button>
                </Col>
                <Col style={{ paddingLeft: '10px', marginTop: '7px' }}>
                    <Button 
                    
                    type="primary" 
                    
                    onClick={onReset}
                    > 
                    Reset 
                    </Button>
                </Col>
                </Row>
            </Form>
      </Card>
      <Table
        columns={columnsSkelton}
        dataSource={data}
        scroll={{ x: 'max-content' }}
        pagination={{
                      current: page,
                      pageSize: pageSize,
                      onChange: (current, size) => {
                        setPage(current);
                        setPageSize(size); 
                      }
                    }}
        bordered/>
    </div>
  );
};

export default IGSTAgingReport;
