import { PurchaseProductFilterReq } from '@gtpl/shared-models/finance';
import { PurchasesProductService } from '@gtpl/shared-services/finance';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { SearchOutlined, FilePdfOutlined, DownloadOutlined } from '@ant-design/icons';

import { Button, Card, Col, Form, Input, Row, Select, Table } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react'
import { Excel } from 'antd-table-saveas-excel';
import jsPDF from 'jspdf';

import Highlighter from 'react-highlight-words';
import { CompanyTypeEnum, PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from '@gtpl/shared-services/masters';

const ProductPurchaseReport = () => {

    const [page,setPage] = useState<number>(1)
    const [purchaseViewData, setPurchaseViewData] = useState([])
    const [vendorNames,setVendorNames]=useState([])
    const [invoiceNumber,setInvoiceNumber]=useState([])
    const [unitCodes,setUnitCodes]=useState([])
    const purchaseService = new PurchasesProductService()

    const {Option}=Select;
    const [form] = Form.useForm();
    const [modalOpen,setModalOpen] = useState<boolean>(false)
    const [purchaseProductDetailedView, setPurchaseProductDetailedView] = useState<any>();
    const role = JSON.parse(localStorage.getItem('role')) 
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [factoriesData, setFactoriesData] = useState([]);
    const unitService = new UnitcodeService();



    useEffect(()=>{
        getPackStyles();
        getAllVendorNames();
        getAllInvoiceNumbers();
        getAllUnits();
        getAllCompanyNames()
    },[])


    const getAllCompanyNames = () => {
        purchaseService.getAllCompanys().then((res) => {
            if (res.status) {
                setFactoriesData(res.data)
            }
        })
    }

    
    
    const getAllVendorNames = () => {
        const req = new PurchaseProductFilterReq()
        if (form.getFieldValue('company') !== undefined) {
            req.company = form.getFieldValue('company')
          }
          if (form.getFieldValue('unitId') !== undefined) {
            req.unitId = form.getFieldValue('unitId')
          }

          const loggedInRole = JSON.parse(localStorage.getItem('role'));
          const loggedInUnitId = Number(localStorage.getItem('unit_id'));
      
          if (loggedInRole !== 'SUPERADMIN') {
            req.unitId = loggedInUnitId // Convert number to string
        }
        purchaseService.getAllVendorNamesForView(req).then((res) => {
            if (res.status) {
                setVendorNames(res.data)
            }
        })
    }
    
    const getAllInvoiceNumbers = () => {
        const req = new PurchaseProductFilterReq()
        if (form.getFieldValue('company') !== undefined) {
            req.company = form.getFieldValue('company')
          }
          if (form.getFieldValue('unitId') !== undefined) {
            req.unitId = form.getFieldValue('unitId')
          }

          const loggedInRole = JSON.parse(localStorage.getItem('role'));
          const loggedInUnitId = Number(localStorage.getItem('unit_id'));
      
          if (loggedInRole !== 'SUPERADMIN') {
            req.unitId = loggedInUnitId // Convert number to string
        }
        purchaseService.getAllInvoiceNumber(req).then((res) => {
            if (res.status) {
                setInvoiceNumber(res.data)
            }
        })
    }
    
    const getAllUnits = () => {
        purchaseService.getAllUnits().then((res) => {
            if (res.status) {
                setUnitCodes(res.data)
            }
        })
    }


    const getPackStyles = () => {
        const req = new PurchaseProductFilterReq()
        if (form.getFieldValue('vendorName') !== undefined) {
            req.vendorName = form.getFieldValue('vendorName')
          }
          if (form.getFieldValue('invoiceNum') !== undefined) {
            req.invoiceNum = form.getFieldValue('invoiceNum')
          }
          if (form.getFieldValue('company') !== undefined) {
            req.company = form.getFieldValue('company')
          }
          if (form.getFieldValue('unitId') !== undefined) {
            req.unitId = form.getFieldValue('unitId')
          }

          const loggedInRole = JSON.parse(localStorage.getItem('role'));
          const loggedInUnitId = Number(localStorage.getItem('unit_id'));
      
          if (loggedInRole !== 'SUPERADMIN') {
            req.unitId = loggedInUnitId // Convert number to string
        }
        console.log(req,'oooooooooooooo')
        purchaseService.getViewForAllProducts(req).then((res) => {
            if (res.status) {
                setPurchaseViewData(res.data)
            }else {
                setPurchaseViewData([])
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        })
    }

    const onReset = () => {
        form.resetFields();
        getPackStyles();
      };

      function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };
    function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
    };
    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
    });


    const Columns: ColumnProps<any>[] = [
        {
           title: 'S No',
           key: 'sno',
           width: '90px',
           responsive: ['sm'],
           render: (text, object, index) => (page - 1) * 10 + (index + 1)
       },
      
       {
           title: "Vendor",
           dataIndex: "vendorName",
           width:"90px",
           sorter: (a, b) => a.vendorName?.localeCompare(b.vendorName),
           sortDirections: ['descend', 'ascend'],
           ...getColumnSearchProps('vendorName')

       },
       {
           title: "Unit",
           dataIndex: "unitName",
           width:"150px",
           sorter: (a, b) => a.unitName?.localeCompare(b.unitName),
           sortDirections: ['descend', 'ascend'],
           ...getColumnSearchProps('unitName')

       },
       {
        title: "Company",
        dataIndex: "company",
        sorter: (a, b) => a.company?.localeCompare(b.company),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('company'),
        render: (text, record) => { return record.company ? record.company : '-' }

    },
       {
           title: "Invoice Number",
           dataIndex: "invoiceNum",
           sorter: (a, b) => a.invoiceNum?.localeCompare(b.invoiceNum),
           sortDirections: ['descend', 'ascend'],
           ...getColumnSearchProps('invoiceNum'),
            render: (text, record) => { return record.invoiceNum ? record.invoiceNum : '-' }


       },
       {
        title: "Product",
        dataIndex: "productName",
        width:"150px",
        sorter: (a, b) => a.productName?.localeCompare(b.productName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('productName')

    },
    {
        title: "Pack Style",
        dataIndex: "packingStyleName",
        sorter: (a, b) => a.packingStyleName?.localeCompare(b.packingStyleName),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('packingStyleName')

    },
    {
        title: "Lot Number",
        dataIndex: "lotNumber",
        width:"150px",
        sorter: (a, b) => a.lotNumber?.localeCompare(b.lotNumber),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('lotNumber')

    },
    {
        title: "Case Weight",
        dataIndex: "caseWeight",
        sorter: (a, b) => parseFloat(a.caseWeight) - parseFloat(b.caseWeight),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('caseWeight'),
        render: (text, record) => {
            const qty = Number(record.caseWeight); // Convert to a number
            return !isNaN(qty) // Check if qty is a valid number
                ? qty % 1 === 0 // Check if qty is a whole number
                    ? qty.toFixed(0) // No decimal places
                    : qty.toFixed(1) // One decimal place
                : '-';
        }
    },
    
    {
        title: "Net Weight",
        dataIndex: "netWeight",
    
        sorter: (a, b) => a.netWeight?.localeCompare(b.netWeight),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('netWeight'),
        render: (text, record) => {
            const qty = Number(record.netWeight); // Convert to a number
            return !isNaN(qty) // Check if qty is a valid number
                ? qty % 1 === 0 // Check if qty is a whole number
                    ? qty.toFixed(0) // No decimal places
                    : qty.toFixed(1) // One decimal place
                : '-';
        }

    },
    {
        title: "Cases",
        dataIndex: "cases",
        sorter: (a, b) => a.cases?.localeCompare(b.cases),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('cases'),
        render: (text, record) => {
            const qty = Number(record.cases); // Convert to a number
            return !isNaN(qty) // Check if qty is a valid number
                ? qty % 1 === 0 // Check if qty is a whole number
                    ? qty.toFixed(0) // No decimal places
                    : qty.toFixed(1) // One decimal place
                : '-';
        }

    },
    {
        title: "Unit Price",
        dataIndex: "unitPrice",
        sorter: (a, b) => a.unitPrice?.localeCompare(b.unitPrice),
        sortDirections: ['descend', 'ascend'],
        ...getColumnSearchProps('unitPrice'),
        render: (text, record) => {
            const qty = Number(record.unitPrice); // Convert to a number
            return !isNaN(qty) // Check if qty is a valid number
                ? qty % 1 === 0 // Check if qty is a whole number
                    ? qty.toFixed(0) // No decimal places
                    : qty.toFixed(1) // One decimal place
                : '-';
        }

    },
    {
        title: "Tax%",
        dataIndex: "taxPercentage",
        sorter: (a, b) => a.taxPercentage?.localeCompare(b.taxPercentage),
        sortDirections: ['descend', 'ascend'],
        render: (text, record) => {
            const qty = Number(record.taxPercentage); // Convert to a number
            return !isNaN(qty) // Check if qty is a valid number
                ? qty % 1 === 0 // Check if qty is a whole number
                    ? qty.toFixed(0) // No decimal places
                    : qty.toFixed(1) // One decimal place
                : '-';
        }

    },
    {
        title: "Amount",
        dataIndex: "totalAmount",
        sorter: (a, b) => a.totalAmount?.localeCompare(b.totalAmount),
        sortDirections: ['descend', 'ascend'],
        fixed:"left",
     
        render: (text, record) => {
            return record.totalAmount 
                ? new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(Number(record.totalAmount)) 
                : '-';
        }



       
    
    },
   ];


   
  const exportedData = [];
  const execlData = purchaseViewData
  let x = 1;
  const data = [
    { title: 'S No', dataIndex: 'sNo', width: 100, height: 40, render: (text, object, index) => { return x++; } },
    { title: 'Vendor', dataIndex: 'vendorName', width: 150, height: 40, render: (text, record) => { return record.vendorName ? record.vendorName : '-' } },
    { title: 'Unit', dataIndex: 'unitName', width: 100, height: 40, render: (text, record) => { return record.unitName ? record.unitName : '-' } },
    { title: 'Company', dataIndex: 'company', width: 150, height: 40, render: (text, record) => { return record.company ? record.company : '-' } },
    { title: 'Invoice Number', dataIndex: 'invoiceNum', width: 150, height: 40, render: (text, record) => { return record.invoiceNum ? record.invoiceNum : '-' } },
    { title: 'Product', dataIndex: 'productName', width: 200, height: 40, render: (text, record) => { return record.productName ? record.productName : '-' } },
    { title: 'Pack Style', dataIndex: 'packingStyleName', width: 150, height: 40, render: (text, record) => { return record.packingStyleName ? record.packingStyleName : '-' } },
    { title: 'Lot Number', dataIndex: 'lotNumber', width: 150, height: 40, render: (text, record) => { return record.lotNumber ? record.lotNumber : '-' } },
    { title: 'Case Weight', dataIndex: 'caseWeight', width: 100, height: 40, render: (text, record) => { return record.caseWeight ? record.caseWeight : '-' } },
    { title: 'Net Weight', dataIndex: 'netWeight', width: 100, height: 40, render: (text, record) => { return record.netWeight ? record.netWeight : '-' } },
    { title: 'Cases', dataIndex: 'cases', width: 100, height: 40, render: (text, record) => { return record.cases ? record.cases : '-' } },
    { title: 'Unit Price', dataIndex: 'unitPrice', width: 100, height: 40, render: (text, record) => { return record.unitPrice ? record.unitPrice : '-' } },
    { title: 'Tax%', dataIndex: 'taxPercentage', width: 100, height: 40, render: (text, record) => { return record.taxPercentage ? record.taxPercentage : '-' } },
    {
        title: 'Amount',
        dataIndex: 'totalAmount',
        width: 100,
        height: 40,
        render: (text, record) => {
            return record.totalAmount 
            ? new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(Number(record.totalAmount)) 
            : '-';
        }
      }
      
];


const exportExcel = () => {
    const excel = new Excel();
  
    // Process purchaseViewData before exporting
    let totalNetWeight = 0;
    let totalAmount = 0;
  
    const processedData = purchaseViewData.map((record) => {
      const netWeight = record.caseWeight && record.cases ? (record.caseWeight * record.cases) : record.netWeight || 0;
      const amountBeforeTax = record.cases && record.unitPrice ? record.cases * record.unitPrice : 0;
      const taxAmount = record.taxPercentage ? (amountBeforeTax * record.taxPercentage) / 100 : 0;
      const totalAmountValue = amountBeforeTax + taxAmount;
  
      // Accumulate totals
      totalNetWeight += parseFloat(netWeight) || 0;
      totalAmount += parseFloat(totalAmountValue.toString()) || 0;
  
      return {
        ...record,
        netWeight: netWeight.toFixed(2),
        totalAmount: totalAmountValue.toFixed(2),
      };
    });
  
    // Append total row
    processedData.push({
      sNo: 'Total', // Label for the total row
      vendorName: '',
      unitName: '',
      company: '',
      invoiceNum: '',
      productName: '',
      packingStyleName: '',
      lotNumber: '',
      caseWeight: '',
      netWeight: totalNetWeight.toFixed(2), // Total Net Weight
      cases: '',
      unitPrice: '',
      taxPercentage: '',
      totalAmount: totalAmount.toFixed(2), // Total Amount
    });
  
    excel
      .addSheet('Purchase-report')
      .addColumns(data)
      .addDataSource(processedData, { str2num: true })
      .saveAs('PurchaseReport.xlsx');
  };
  
  


  const exportToPdf = () => {
    var columns = [
        { title: 'S No', dataIndex: 'sNo', render: (text, object,index) => { return x++; } },
        { title: 'Vendor', dataIndex: 'vendorName', render: (text, record) => { return record.vendorName ? record.vendorName : '-' } },
        { title: 'Unit', dataIndex: 'unitName', render: (text, record) => { return record.unitName ? record.unitName : '-' } },
        { title: 'Company', dataIndex: 'company', render: (text, record) => { return record.company ? record.company : '-' } },
        { title: 'Invoice Number', dataIndex: 'invoiceNum', render: (text, record) => { return record.invoiceNum ? record.invoiceNum : '-' } },
        { title: 'Product', dataIndex: 'productName', render: (text, record) => { return record.productName ? record.productName : '-' } },
        { title: 'Pack Style', dataIndex: 'packingStyleName', render: (text, record) => { return record.packingStyleName ? record.packingStyleName : '-' } },
        { title: 'Lot Number', dataIndex: 'lotNumber', render: (text, record) => { return record.lotNumber ? record.lotNumber : '-' } },
        { title: 'Case Weight', dataIndex: 'caseWeight', render: (text, record) => { return record.caseWeight ? record.caseWeight : '-' } },
        { title: 'Net Weight', dataIndex: 'netWeight', render: (text, record) => { return record.netWeight ? record.netWeight : '-' } },
        { title: 'Cases', dataIndex: 'cases', render: (text, record) => { return record.cases ? record.cases : '-' } },
        { title: 'Unit Price', dataIndex: 'unitPrice', render: (text, record) => { return record.unitPrice ? record.unitPrice : '-' } },
        { title: 'Tax%', dataIndex: 'taxPercentage', render: (text, record) => { return record.taxPercentage ? record.taxPercentage : '-' } },
        { title: 'Amount', dataIndex: 'totalAmount', render: (text, record) => { return record.totalAmount ? record.totalAmount : '-' } },
    
    ];
    const doc = new jsPDF()
    // @ts-ignore

    doc.autoTable(columns, purchaseViewData, {
      columnStyles: {
        id: { fillColor: 255 }
      },

      margin: { top: 20 },
      addPageContent: function (data) {
        doc.text("PURCHASE REPORT", 50, 15);
      }
    });
    doc.save('purchase-report.pdf')
  }

  return (
    <div>
         <Card title={<span style={{ color: 'white' }} > Purchase Report</span>}
            style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            extra={
                <span>
                    {/* <Button icon={<FilePdfOutlined />} style={{ marginRight: 5 }} onClick={() => { exportToPdf(); }}>
                        Get PDF
                    </Button> */}
                    <Button className='panel_button' onClick={() => exportExcel()}>Get Excel</Button>
                </span>
            }
           >
            <Form layout='vertical' form={form} onFinish={getPackStyles}>
                <Row gutter={24}>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 5 }} xl={{ span: 5 }}>
                        <Form.Item name="vendorName" label="Vendor" >
                            <Select
                                placeholder="Select Vendor"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                allowClear
                                dropdownMatchSelectWidth={false}


                            >
                                {vendorNames.map(dropData => {
                                    return <Option value={dropData.vendorId}>{dropData.vendorName}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                        <Form.Item name="invoiceNum" label="Invoice Number" >
                            <Select
                                placeholder="Select Invoice Number"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                allowClear
                                dropdownMatchSelectWidth={false}


                            >
                                {invoiceNumber.map(dropData => {
                                    return <Option value={dropData.purchaseId}>{dropData.invoiceNum}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                        <Form.Item name="company" label="Company" >
             
                   
                            <Select
                                placeholder="Select Company"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                allowClear
                                dropdownMatchSelectWidth={false}

                            >
                                {factoriesData.map(dropData => {
                                    return <Option value={dropData.company}>{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="unitId" label="Unit"
                        //  rules={[{ required: true, message: 'Missing Unit' }]}
                         >
                            <Select
                                placeholder="Select Unit"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                allowClear
                                disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                                defaultValue={role == 'SUPERADMIN' ? 'all' : Number(localStorage.getItem('unit_id'))}
                            >
                               {unitCodes.map(dropData => {
                                    return <Option value={dropData.unitCodeId}>{dropData.unitName}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={12} sm={6} md={4} lg={3} xl={2} style={{paddingTop:"25px", marginTop:'5px'}}>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                // style={{ background: "green", width: "100%" }}
              >
                Get Report
              </Button>
            </Form.Item>
          </Col>
          <Col xs={12} sm={6} md={4} lg={3} xl={2} style={{paddingTop:"25px", marginTop:'5px',marginLeft:30}}>
            <Form.Item>
              <Button
                type="primary"
                // icon={<UndoOutlined />}
                onClick={onReset}
                style={{ width: "100%" }}
              >
                Reset
              </Button>
            </Form.Item>
          </Col>
                </Row>
            </Form>
            <Table columns={Columns} dataSource={purchaseViewData}  scroll={{x:true}}
             summary={(pageData) => {
                                  let totalNetWeight = 0;
                                  let totalAmountt=0
                                
                                  pageData.forEach(({ netWeight,totalAmount}) => {
                                      totalNetWeight += parseFloat(netWeight) || 0;
                                      totalAmountt += parseFloat(totalAmount) || 0;
            
                                    });
                                
                                  return (
                                    <Table.Summary.Row>
                                      <Table.Summary.Cell index={8} colSpan={9}>
                                        Total
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={9}>
                                        {totalNetWeight.toFixed(2)}
                                      </Table.Summary.Cell>
                        
                                      <Table.Summary.Cell index={11}>
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={12}>
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={12}>
                                      </Table.Summary.Cell>
                                      <Table.Summary.Cell index={13}>
                                        {totalAmountt.toFixed(2)}
                                      </Table.Summary.Cell>
                                    </Table.Summary.Row>
                                  );
                                }}
            />
            </Card>
    </div>
  )
}

export default ProductPurchaseReport