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 {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 { ReceivablesDetailsReq } from '@gtpl/shared-models/finance';
import { Excel } from 'antd-table-saveas-excel';
import { log } from 'console';
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";



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

export function ReceivablesDetailsReport(
  props: ReceivablesDetailsReportProps
) {
  const [data, setData] = useState([])
  const [page, setPage] = React.useState(1); 
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("")
  const searchInput = useRef(null);
  const service = new CollectionsService()
  const[form] = useForm()
  const { Text } = Typography;

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

  const getData = () => {
    const req =new ReceivablesDetailsReq(moment(form.getFieldValue('year')).format('YYYY'))
    
    service.getReceivablesDetailsReport(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 columns: any[] = [
    {
      title: 'S No',
      key: 'id',
      width: '70px',
      responsive: ['md'],
      align: 'left',
      fixed:'left',
      render: (text, object, index) => (page-1) * 10 +(index+1)

  },
    // {
    //   title: 'S No', dataIndex: 'sNo', render: (text, object, index) => {
    //     if (index == data.length) {
    //       return null;
    //     } else {
    //       return index + 1
    //     }
    //   },
    //   width: 60,

    // },
    {
      title: 'PO Number', 
     dataIndex: 'poNum',
     width:'200px',
     fixed:'left',
     align:'left',
       render: (text: any, record: any) => { return record.poNum? record.poNum : '-' },
       sorter: (a, b) => a.poNum.localeCompare(b.poNum),
     sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('poNum')

    },
    {
      title: 'Invoice Number', 
     dataIndex: 'invoiceNum',
     width:'200px',

     align:'left',
            render: (text: any, record: any) => { return record.invoiceNum? record.invoiceNum : '-' },
       sorter: (a, b) => a.invoiceNum.localeCompare(b.invoiceNum),
     sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('invoiceNum')
    },
    {
      title: 'Invoice Date', 
     dataIndex: 'invDate',
     width:'100px',

       render: (text: any, record: any) => { return record.invDate ? moment(record.invDate).format('DD-MM-YYYY') : '-' },
       sorter: (a, b) => a.invDate.localeCompare(b.invDate),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'BL Date', 
     dataIndex: 'blDate',
width:'100px',
render: (text: any, record: any) => { 
  console.log(typeof (record.blDate),'000000000');
  return record.blDate ? moment(record.blDate).format('DD-MM-YYYY') : '-' },
  // sorter: (a, b) => {
  //   const aDate = moment(a.blDate);
  //   const bDate = moment(b.blDate);
  //   // console.log(aDate - bDate,'ppppppppppp');
    
  //   // Use timestamps to handle sorting for both Date and string formats
  //   return aDate.isValid() && bDate.isValid() ? aDate.valueOf()?aDate.valueOf():0- bDate.valueOf()?bDate.valueOf():0 : 0;
  // },
  // sortDirections: ['descend', 'ascend'],
}, 
    {
      title: 'ETA', 
     dataIndex: 'eta',
     width:'100px',

       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: 'CustomerName', 
     dataIndex: 'customerName',
     width:'200px',
     ...getColumnSearchProps('customerName'),
       render: (text: any, record: any) => { return record.customerName ?  record.customerName : '-' },
       sorter: (a, b) => a.customerName.localeCompare(b.customerName),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Invoice Amt. USD', 
      width:'100px',
     dataIndex: 'totalAmount',
     align:'right',
       render: (text: any, record: any) => { return record.totalAmount? Number(record.totalAmount).toLocaleString() : '-' },
       sorter: (a, b) => a.totalAmount.localeCompare(b.totalAmount),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Part Payment received', 
     dataIndex: 'collection',
     width:'100px',
     align:'right',
       render: (text: any, record: any) => { return record.collection?  Number(record.collection).toLocaleString() : '-' },
       sorter: (a, b) => a.collection.localeCompare(b.collection),
     sortDirections: ['descend', 'ascend'],
    }, 
    {
      title: 'Balance Receivable', 
    //  dataIndex: 'totalAmount',
     width:'100px',
     align:'right',
      sorter: (a, b) => a.totalAmount.localeCompare(b.totalAmount),
     sortDirections: ['descend', 'ascend'],
     render:(val,rec)=>{
      const amt =Number(rec.totalAmount?rec.totalAmount:0) -Number(rec.collection?rec.collection:0)
      return (<span>{Number(amt).toLocaleString()}</span>) 
     }
    },
    {
      title: 'Received Date', 
     dataIndex: 'receivedDate',
     width:'100px',

       render: (text: any, record: any) => { return record.receivedDate ? moment(record.receivedDate).format('DD-MM-YYYY') : '-' },
       sorter: (a, b) => a.receivedDate.localeCompare(b.receivedDate),
     sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'PAYMENT TERM', 
     dataIndex: 'paymentTerm',
     width:'100px',
     align:'center',
       render: (text: any, record: any) => { return record.paymentTerm? record.paymentTerm : '-' },
       sorter: (a, b) => a.paymentTerm.localeCompare(b.paymentTerm),
     sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('paymentTerm'),

    },
    {
      title: 'BANK NAME', 
     dataIndex: 'bank',
     width:'150px',
     align:'center',
       render: (text: any, record: any) => { return record.bank? record.bank : '-' },
       sorter: (a, b) => a.bank.localeCompare(b.bank),
     sortDirections: ['descend', 'ascend'],
     ...getColumnSearchProps('bank'),

    },
    {
      title: 'Remarks', 
     dataIndex: 'remarks',
     width:'150px',
          align:'center',
      
    },
  ]

const exportExcel = async () => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("Receivables Detail Report");

  // Define columns (ignore columns without dataIndex)
  worksheet.columns = columns
      .filter(col => col.dataIndex) // Ignore columns without dataIndex
      .map(col => ({
          header: col.title,
          key: col.dataIndex,
          width: 20,
      }));

  // Apply background color to headers
  const headerRow = worksheet.getRow(1);
  headerRow.eachCell((cell) => {
      cell.fill = {
          type: "pattern",
          pattern: "solid",
          fgColor: { argb: "008000" }, // Green background
      };
      cell.font = { bold: true, color: { argb: "FFFFFF" } }; // White text
      cell.alignment = { horizontal: "center" };
  });

  // Add data (including computed "Balance Receivable" and formatted dates)
  data.forEach((record) => {
      worksheet.addRow({
          ...record,
          invDate: record.invDate ? moment(record.invDate).format("DD-MM-YYYY") : "-",
          blDate: record.blDate ? moment(record.blDate).format("DD-MM-YYYY") : "-",
          eta: record.eta ? moment(record.eta).format("DD-MM-YYYY") : "-",
          receivedDate: record.receivedDate ? moment(record.receivedDate).format("DD-MM-YYYY") : "-",
          balanceReceivable: Number(record.totalAmount || 0) - Number(record.collection || 0), // Compute balance
      });
  });

  // Generate and save file
  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  });
  saveAs(blob, "Receivables Detail Report.xlsx");
};


  
  const onReset = () => {
    form.resetFields();
    getData();
  };
  return (
    
    <Card size="small" title={<span style={{ color: 'white' }} > Receivables Detail Report</span>}
    style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    extra={
      <div>
        <Button icon={<DownloadOutlined />} onClick={exportExcel} style={{marginRight:30}}>
          Get Excel
        </Button></div>}
    >
      <Form form={form} onFinish={search} layout="vertical">
            <Row gutter={24}>
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 4 }} xl={{ span: 4}}>

                <Form.Item label='Year' name='year' >
                <DatePicker  picker="year" placeholder="Select Year" />
                </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} scroll={{x:'max-content',y:1024}}
      bordered
      pagination={{
        onChange(current) {
          setPage(current);
        }
    }}
      summary={(pageData) => {
        let paid = 0;
        let bal = 0
        let totAmt = 0
        
        pageData.forEach((e) => {
           paid+= Number(e.collection);
          bal += Number(e.totalAmount?e.totalAmount:0-e.collection?e.collection:0);
          totAmt += Number(e.totalAmount);

        });

        return (
          <>
            <Table.Summary.Row className='tableFooter' >
              <Table.Summary.Cell index={1} ><Text ></Text></Table.Summary.Cell>
              <Table.Summary.Cell index={8} colSpan={6}><Text style={{ textAlign: 'end' }}>Total</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={9}><Text style={{ textAlign: 'end' }}>{Number(totAmt).toLocaleString()}</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={10}><Text style={{ textAlign: 'end' }}>{Number(paid).toLocaleString()}</Text></Table.Summary.Cell>
              <Table.Summary.Cell index={11}><Text style={{ textAlign: 'end' }}>{Number(totAmt-paid).toLocaleString()}</Text></Table.Summary.Cell>
            </Table.Summary.Row>
          </>
        );
      }
      }/>
     ):'No Data Found'}
    </Card>
  );
}

export default ReceivablesDetailsReport;
