import React, { useRef, useState, useEffect } from 'react';
import { Table, Card, Input, Button, Tooltip, Form, Col, Row, Select, Modal, Empty, Popconfirm, message, Tabs, DatePicker, Typography, Pagination, Descriptions, Statistic, Spin, Alert } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import { SearchOutlined, FileExcelOutlined, FilePdfOutlined, WhatsAppOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { FGStockService, StockInService } from '@gtpl/shared-services/warehouse-management';
import './stock-grid.css';
import { useHistory } from 'react-router-dom';
import moment from 'moment';
import { MessageRequest, ShiftsDropDown, StockInTransactionsRequest, StockTypeDropDown, StockTypesEnum, StockTypeStatus, UnitRequest } from '@gtpl/shared-models/common-models';
import { Excel } from 'antd-table-saveas-excel';
import jsPDF from 'jspdf'
import 'jspdf-autotable'
import { MasterBrandService, SkuService } from '@gtpl/shared-services/masters';
import { MasterBrandDto, MasterBrandsDropDownDto } from '@gtpl/shared-models/masters';
// import {MasterBrandsService} from '@gtpl/shared-srvices/MasterBrandsService'
import { UnitcodeService } from '@gtpl/shared-services/masters';
import {WhatsAppNotificationService} from '@gtpl/shared-services/notification-management'


const { Option } = Select;
/* eslint-disable-next-line */
export interface StockInTransctionsReportProps {

}


export function StockInTransactionsReport(props: StockInTransctionsReportProps) {
    const { Text } = Typography;
    const [form] = Form.useForm();
    const searchInput = useRef(null);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const stockService = new FGStockService();
    const [page, setPage] = React.useState(1);
    const { RangePicker } = DatePicker;
    const [stockinTransactionsData, setStockinTransactionsData] = useState<any>([])
    const [unitData, setunitData] = useState<any[]>([]);
    const unitsService = new UnitcodeService();
    const [loading, setLoading] = useState<boolean>(false)
    const [empty, setEmpty] = useState<boolean>(false)
    let totalReportedCases = 0;
    const unitId = Number(localStorage.getItem('unit_id'));
    const [product, setProduct] = useState<any>()
    const productService = new SkuService()
    const [pageSize, setPageSize] = useState<number>(null);
    const [disable, setDisable] = useState<boolean>(false)
    const [brandfiltersData, setFiltersData] = useState<any[]>([]);
    // const [selectedunit, setUnit] = useState<number>(0)
    const [selectedEstimatedFromDate, setSelectedEstimatedFromDate] = useState(undefined);
    const [selectedEstimatedToDate, setSelectedEstimatedToDate] = useState(undefined);
    const [productfiltersData, setproductFiltersData] = useState<any[]>([]);
    const [brandsDropDown, setBrandsDropDown] = useState<MasterBrandsDropDownDto[]>([]);
    const [visible, setVisible] = useState<boolean>(false)
    const [unit, setUnit] = useState<any[]>([])
    const fgservice = new FGStockService();
    const brandsService = new MasterBrandService();
    const [modalForm] = Form.useForm();
    const whatsAppService = new WhatsAppNotificationService
    const [productData, setProductData] = useState<any[]>([]);
    const stockInService = new StockInService();
   let totalLoosePouches=0;



    useEffect(() => {
        if (Number(localStorage.getItem('unit_id')) != 5) {
            form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
        }
        getAllPlants()
        form.setFieldsValue({
            createdAt: [(moment(moment().format("YYYY-MM-DD")).subtract(1, 'days')), moment(moment().format("YYYY-MM-DD"))]
        })
        setSelectedEstimatedFromDate((moment(moment().format("YYYY-MM-DD")).subtract(1, 'days')))
        setSelectedEstimatedToDate(moment(moment().format("YYYY-MM-DD")))
        getUnitDropdownForStockInReport()
        getStockInTransactions()
        setEmpty(true)
        getProductDropForStockReport();
    }, [])



    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 getUnitDropdownForStockInReport = () => {
        fgservice.getUnitDropdownForStockInReport().then((res) => {
            if (res.status) {
                setUnit(res.data);
            } else {
                setUnit(res.data);
            }
        }).catch(err => {
            AlertMessages.getErrorMessage(err.message);
        })
    }
    const getProductDropForStockReport = () => {
        stockInService.getProductDropForStockReport({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) => {
          if (res.status) {
            // console.log(res.data);
            setProductData(res.data);
          } else {
            if (res.intlCode) {
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
            setProductData([]);
          }
        }).catch((err) => {
          AlertMessages.getErrorMessage(err.message);
          setProductData([]);
    
        });
      }
    const getAllPlants = () => {
        unitsService.getAllMainPlants().then((res) => {
            if (res.status) {
                    setunitData(res.data) 
            } else {
                setunitData([]);
            }
        }).catch(err => {
            AlertMessages.getErrorMessage(err.message);
            setunitData([]);
        })
    }

    function unique(data, key) {
        return [
            ...new Map(
                data.map(x => [key(x), x])
            ).values()
        ]
    }

    const handleUnit = (value) => {
        // setUnit(value)
    }


    const getStockInTransactions = () => {
        // Check if any filters are selected
        const hasFilters =
            form.getFieldValue('reportingDate') ||
            form.getFieldValue('unitId') ||
            form.getFieldValue('createdAt') ||
            form.getFieldValue('product');
    
        setLoading(true);
        setEmpty(false);
        // setDisable(true);
    
        const req = new StockInTransactionsRequest();
        const unitId = Number(localStorage.getItem('unit_id'));
        const dropdownUnitId = form.getFieldValue('unitId');
    
        // Set unitId based on the condition
        if (unitId == 5 && dropdownUnitId) {
            req.unitId = dropdownUnitId;
        } else {
            req.unitId = dropdownUnitId;
        }
    
        // Only apply filters if at least one is selected
        if (hasFilters) {
            if (form.getFieldValue('product')) {
                req.product = form.getFieldValue('product');
            }
            if (form.getFieldValue('reportingDate') !== undefined) {
                const selectedFromDate = moment(form.getFieldValue('reportingDate')[0]).format('YYYY-MM-DD');
                const selectedToDate = moment(form.getFieldValue('reportingDate')[1]).format('YYYY-MM-DD');
                req.reportedFromData = selectedFromDate;
                req.reportedToData = selectedToDate;
            }
            if (form.getFieldValue('createdAt')) {
                const selectedFromDate = moment(form.getFieldValue('createdAt')[0]).format('YYYY-MM-DD');
                const selectedToDate = moment(form.getFieldValue('createdAt')[1]).format('YYYY-MM-DD');
                req.transactionFromDate = selectedFromDate;
                req.transactionToDate = selectedToDate;
            }
        }
    
        // Fetch data
        stockService.getStockInTransactions(req).then((res) => {
            // setDisable(false);
            setLoading(false);
            if (res.status) {
                setStockinTransactionsData(res.data);
                
                // Data for brands filter
                let filtersArray = [];
                let uniq = res.data.filter((thing, index, self) =>
                    index === self.findIndex((t) => t.brandName === thing.brandName)
                );
                uniq.map(item => {
                    if (!filtersArray.some(filter => filter.value === item.brandName)) {
                        filtersArray.push({ text: item.brandName, value: item.brandName });
                    }
                });
    
                // Data for products filter
                let productFiltersArray = [];
                let produtsUniq = res.data.filter((thing, index, self) =>
                    index === self.findIndex((t) => t.variantCode === thing.variantCode)
                );
                produtsUniq.map(item => {
                    if (!productFiltersArray.some(filter => filter.value === item.variantCode)) {
                        productFiltersArray.push({ text: item.variantCode, value: item.variantCode });
                    }
                });
    
                setproductFiltersData(
                    productFiltersArray.sort((a, b) => {
                        const [key1, key2] = [a.text.split('/')[0], b.text.split('/')[0]];
                        return Number(key1.split('-')[0]) - Number(key2.split('-')[0]);
                    })
                );
                setFiltersData(filtersArray);
            } else {
                setStockinTransactionsData([]);
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        }).catch(() => {
            // setDisable(false);
            setLoading(false);
            // AlertMessages.getErrorMessage('Something went wrong');
        });
    };
    

    const shareData = () => {
        setVisible(true)
    }
    const onCancel = () => {
        setVisible(false)
    }

    const sendMessage = () => {
        const phNo = modalForm.getFieldValue('number')
        const req = new MessageRequest('91' + phNo,'hello','hi','dileep')
        whatsAppService.sendPersonalMessage(req).then(res => {
            if(res.status){
                AlertMessages.getSuccessMessage('message sent')
                setVisible(false)
            }
        })
    }


    const EstimatedETDDate = (value) => {
        console.log(value, 'value')
        if (value) {
            const fromDate = new Date(value[0].format('YYYY-MM-DD'));
            const toDate = new Date(value[1].format('YYYY-MM-DD'));
            setSelectedEstimatedFromDate(fromDate)
            setSelectedEstimatedToDate(toDate)
        }
    }


    function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    }

    function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');

    }


    /**
    * 
    * @param pagination 
    * @param filters 
    * @param sorter 
    * @param extra 
    */
    const onChange = (pagination, filters, sorter, extra) => {
        console.log('params', pagination, filters, sorter, extra);
    }

    const onReset = () => {
        form.resetFields();
        if (Number(localStorage.getItem('unit_id')) != 5) {
            form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
        }
        // setStockinTransactionsData([])
        setEmpty(true)
        getStockInTransactions()

    };

    const columnsSkelton: ColumnProps<any>[] = [

        {
            title: 'S No',
            key: 'sno',
            width: '70px',
            render: (text, object, index) => (page - 1) * pageSize + (index + 1)
        },
        {
            title: 'Unit',
            dataIndex: 'unitName',
            width: "150px",
        },
        {
            title: 'Stock Type',
            dataIndex: 'stockType',
            width: 120,
            sorter: (a, b) => a.stockType.length - b.stockType.length || a.stockType.localeCompare(b.stockType),
            sortDirections: ['descend', 'ascend'],
            // ...getColumnSearchProps('stockType'),
            responsive: ["lg"],
            filters: [
                { text: 'Anticipated', value: 'anticipated' },
                { text: 'Dummy', value: 'dummy' },
                { text: 'SaleOrder', value: 'SaleOrder' },
                { text: 'SuperDummy', value: 'superDummy' },
            ],
            filterMultiple: true,
            onFilter: (value, record) => {
                return record.stockType == value;
            },
        },


        {
            title: 'Rack Position',
            dataIndex: 'rackCode',
            width: 100,
            sorter: (a, b) => a.rackCode.toString().length - b.rackCode.toString().length || a.rackCode.toString().localeCompare(b.rackCode.toString()),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('rackCode'),
        },
         {
            title: 'Lot code',
            dataIndex: 'lotCode',
            width: 100,
            sorter: (a, b) => a.lotCode.toString().length - b.lotCode.toString().length || a.lotCode.toString().localeCompare(b.lotCode.toString()),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('lotCode'),
        },
        {
            title: 'Customer PO',
            dataIndex: 'poNumber',
            width: 120,
            // sorter: (a, b) => a.saleOrderNumber.length - b.saleOrderNumber.length || a.saleOrderNumber.localeCompare(b.saleOrderNumber),
            sorter: (a, b) => a.poNumber.localeCompare(b.poNumber),
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('poNumber'),
        },
        {
            title: 'Brand',
            dataIndex: "brandName",
            width: 140,
            // sorter: (a, b) => a.brandName.localeCompare(b.brandName),
            sortDirections: ['descend', 'ascend'],
             ...getColumnSearchProps('brandName')
            // filters: brandfiltersData,

            // filterMultiple: true,
            // onFilter: (value, record) => {
            //     return record.brandName == value;
            // },
            // render: (text, record) => { return record.brandName ? record.brandName : '-' }



        },
        {
            title: 'Product SKU',
            dataIndex: 'shortCode',
            width: 200,
            // sorter: (a, b) => a.variantCode.localeCompare(b.variantCode),
            //   sortDirections: ['descend', 'ascend'],
            // ...getColumnSearchProps('variantCode'),
            // filters: productfiltersData,

            // filterMultiple: true,
            // onFilter: (value, record) => {
            //     return record.variantCode == value;
            // },
            // render: (value) => (<span style={{ float: 'right' }}>{value}</span>)
            render: (text, record) => { return record.shortCode ? record.shortCode : '-' }

        },
        {
            title: 'Product Category',
            dataIndex: 'productCategory',
            width: 120,
            // sorter: (a, b) =>  a.productCategory?.localeCompare(b.productCategory),
            // sortDirections: ['descend', 'ascend'],
            // ...getColumnSearchProps('productCategory'),
            responsive: ["lg"],
            filters: [
                { text: 'Over Count', value: 'overcount' },
                { text: 'Under Count', value: 'undercount' },
                { text: 'G1', value: 'g1' },
                { text: 'G2', value: 'g2' },
                { text: 'Cut', value: 'cut' },
                { text: 'RJ(Rejections)', value: 'RJ(Rejections)' },
            ],
            filterMultiple: true,
            onFilter: (value, record) => {
                return record.productCategory == value;
            },
            render: (value) => value ? value : '-'
        },
        {
            title: 'Pack Style',
            dataIndex: 'packStyle',
            width: 120,
            ...getColumnSearchProps('packStyle'),
        },
        {
            title: 'Reporting Cases',
            dataIndex: "reportingCases",
            width: 120,
            sorter: (a, b) => a.reportingCases - b.reportingCases,
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('reportingCases'),
            render: (value) => <span style={{ float: 'right' }}>{value}</span>
        },
        {
            title: 'Reporting LoosePouches',
            dataIndex: "loosePouches",
            width: 120,
            sorter: (a, b) => a.loosePouches - b.loosePouches,
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('loosePouches'),
            render: (value) => <span style={{ float: 'right' }}>{value}</span>
        },
        {
            title: 'Pouches Shortage',
            dataIndex: 'pouchShortage',
            width: 100,
            filters: [
                { text: 'YES', value: 'YES' },
                { text: 'NO', value: 'NO' },
            ],
            filterMultiple: false,
            onFilter: (value, record) => {
                return record.pouchShortage === value;
            },

        },
        {
            title: 'Cartons Shortage',
            dataIndex: 'cartonShortage',
            width: 100,
            filters: [
                { text: 'YES', value: 'YES' },
                { text: 'NO', value: 'NO' },
            ],
            filterMultiple: false,
            onFilter: (value, record) => {
                return record.cartonShortage === value;
            },

        },
        {
            title: 'Shift',
            dataIndex: 'shift',
            width: 100,
            filters: [
                { text: 'Shift A', value: 'shiftA' },
                { text: 'Shift B', value: 'shiftB' },
                { text: 'Shift C', value: 'shiftC' },
                { text: 'General', value: 'general' },
            ],
            filterMultiple: true,
            onFilter: (value, record) => {
                return record.shift === value;

            },
            sorter: (a, b) => a.shift - b.shift,
            sortDirections: ['descend', 'ascend'],
            ...getColumnSearchProps('shift'),
        },

        {
            title: 'Warehouse Incharge',
            dataIndex: 'whIncharge',
            width: 150,
            ...getColumnSearchProps('whIncharge'),
            render: (value) => value ? value : '-'
        },


        {
            title: 'Reported Date',
            dataIndex: 'reportingDate',
            width: 100,
            key: 'reportingDate',
            render: (value) => (<span style={{ float: 'right' }}>{moment(value).format("DD-MM-YYYY")}</span>),
            sorter: (a, b) => a.reportingDate.localeCompare(b.reportingDate),
            sortDirections: ['descend', 'ascend'],

        },
        {
            title: 'Created Date',
            dataIndex: 'createdAt',
            width: 100,
            key: 'createdAt',
            render: (value) => (<span style={{ float: 'right' }}>{moment(value).format("DD-MM-YYYY")}</span>),
            sorter: (a, b) => a.createdAt.localeCompare(b.createdAt),
            sortDirections: ['descend', 'ascend'],
        },
        // {
        //   title: 'Cold Storage',
        //   dataIndex: 'coldStorage',
        //   sorter: (a, b) => a.coldStorage.length - b.coldStorage.length || a.coldStorage.localeCompare(b.coldStorage),
        //   sortDirections: ['descend', 'ascend'],
        //   ...getColumnSearchProps('coldStorage'),
        // },
        {
            title: "Transaction Type",
            dataIndex: "transactionType",
            width: 140,
            render: (value) => (<span style={{ float: 'right' }}>{value === 'rm'?'Fresh Production':value}</span>),
            filters: [
                { text: 'palleting', value: 'palleting' },
                { text: 'repalleting', value: 'repalleting' },
                { text: 'repacking', value: 'repacking' },
                { text: 'reprocessing', value: 'reprocessing' },
                { text: 'dispatch', value: 'dispatch' },
                { text: 'unregistered', value: 'unregistered' },
                { text: 'stockTransfer', value: 'stockTransfer' },
                { text: 'Fresh Production', value: 'rm' }
            ],
            filterMultiple: true,
            onFilter: (value, record) => {
                console.log(value); 
                return record.transactionType == value;
            },
        },
        {
            title:"Remarks",
            dataIndex:"remarks",
            width: 100,
            render: (status, rowData) => (
                <>
                  {rowData.remarks? rowData.remarks : '-'}
    
                </>
              ),
        }
    ];


    const data = [
        { title: "Sno", dataIndex: "sno", render: (text, object, index) => (page - 1) * 10 + (index + 1) },
        { title: 'Unit', dataIndex: 'unitName' },
        { title: 'Stock Type', dataIndex: 'stockType' },
        { title: "Rack Position", dataIndex: "rackCode" },
        { title: "Customer PO", dataIndex: "poNumber" },
        { title: 'Brand', dataIndex: 'brandName' },
        { title: "Product SKU", dataIndex: "shortCode" },
        { title: 'Product Category', dataIndex: 'productCategory' },
        { title: "Reporting Cases", dataIndex: "reportingCases", string2Num: true },
        { title: "Loose Pouches", dataIndex: "loosePouches" },
        { title: "Pack Style", dataIndex: "packStyle" },
        { title: "Pouch Shortage", dataIndex: "pouchShortage" },
        { title: "Carton Shortage", dataIndex: "cartonShortage" },
        { title: "Shift", dataIndex: "shift" },
        { title: 'WH Incharge', dataIndex: 'whIncharge' },
        { title: "Reported Date", dataIndex: "reportingDate", render: (value) => moment(value).format("DD-MM-YYYY") },
        { title: "Created Date", dataIndex: "createdAt", render: (value) => moment(value).format("DD-MM-YYYY") },
        { title: "Transaction Type", dataIndex: "transactionType", render: (value) => value === 'rm'?'Fresh Production':value},
    ];

    const exportExcel = () => {
        const excel = new Excel();
        excel
            .addSheet('Stock-In Transactions')
            .addColumns(data)
            .addDataSource(stockinTransactionsData, { str2num: true })
            .saveAs('stock-in-transactions.xlsx');
    }
    const exportToPdf = () => {

        var columns = [
            { title: "Sno", dataKey: "sno", render: (text, object, index) => (page - 1) * 10 + (index + 1) },
            { title: 'Stock Type', dataKey: 'stockType' ,width:20 },
            { title: "Rack Position", dataKey: "rackCode",width:20 },
            { title: "Customer PO", dataKey: "poNumber" ,width:20},
            { title: 'Brand', dataKey: 'brandName',width:20 },
            { title: "Product SKU", dataKey: "shortCode",width:20 },
            { title: 'Product Category', dataKey: 'productCategory',width:20 },
            { title: "Loose Pouches", dataKey: "loosePouches",width:20 },
            { title: "Reporting Cases", dataKey: "reportingCases",width:20 },
            { title: "Pack Style", dataKey: "packStyle" ,width:20},
            { title: "Pouch Shorthage", dataKey: "pouchShortage",width:20 },
            { title: "Carton Shortage", dataKey: "cartonShortage",width:20 },
            { title: "Shift", dataKey: "shift",width:20 },
            { title: 'WH Incharge', dataKey: 'whIncharge',width:20 },
            { title: "Reported Date", dataKey: "reportingDate",width:20, render: (value) => moment(value).format("DD-MM-YYYY") },
            { title: "Created", dataKey: "createdAt",width:20, render: (value) => moment(value).format("DD-MM-YYYY") },
            { title: "Transaction Type", dataKey: "transactionType",width:20 },

        ];
        const doc = new jsPDF('landscape', 'pt', 'a4')
      
        // @ts-ignore

        doc.autoTable(columns, stockinTransactionsData, {
            margin: { top: 50, left: 20, right: 20, bottom: 30 },
            styles: { overflow: 'linebreak', fontSize: 8 },
            columnStyles: {
                sno: { cellWidth: 20 },
                stockType: { cellWidth: 40 },
                rackCode: { cellWidth: 40 },
                poNumber: { cellWidth: 40 },
                brandName: { cellWidth: 40 },
                shortCode: { cellWidth: 40 },
                productCategory: { cellWidth: 40 },
                reportingCases: { cellWidth: 40 },
                packStyle: { cellWidth: 40 },
                pouchShortage: { cellWidth: 40 },
                cartonShortage: { cellWidth: 40 },
                shift: { cellWidth: 20 },
                loosePouches: { cellWidth: 40 },
                whIncharge: { cellWidth: 40 },
                reportingDate: { cellWidth: 40 },
                createdAt: { cellWidth: 40 },
                transactionType: { cellWidth: 40 }
            },
            didDrawPage: function (data) {
                // Header
                doc.setFontSize(14);
                doc.text('STOCK IN TRANSACTIONS', data.settings.margin.left, 40);
    
                // Footer
                var str = "Page " + data.pageCount;
                doc.setFontSize(10);
                var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
                doc.text(str, data.settings.margin.left, pageHeight - 10);
            }
        });
    
        doc.save('stock-in-transactions.pdf');
    };

    return (
        <Card
            title={<span style={{ color: 'white' }}>Stock In Transactions</span>}
            style={{ textAlign: 'center' }}
            headStyle={{ backgroundColor: '#69c0ff', border: 0 }} 
            extra={stockinTransactionsData.length > 0 && (

                
                <Button icon={<FileExcelOutlined />}  onClick={() => { exportExcel(); }}>
                    Get Excel
                </Button>
                               
    )}
    >

            <Form form={form} layout={'vertical'} style={{ padding: '0px' }} >
                {/* <Form.Item
                    style={{ display: "none" }}
                    name="plantId" initialValue={Number(localStorage.getItem('unit_id'))}>
                    <Input hidden />
                </Form.Item> */}
                <Row gutter={[24, 24]}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                        <Form.Item name="reportingDate" label="Reported Date" rules={[{
                            required: false,
                            message: "Reported Date",

                        },
                        ]}>
                            <RangePicker format="DD-MM-YYYY" />
                        </Form.Item>
                    </Col>

                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                        <Form.Item name="createdAt"
                            label="Created Date"
                            initialValue={undefined}
                            rules={[{
                                required: false,
                                message: "Transaction Date"
                            },
                            ]}>
                            <RangePicker onChange={EstimatedETDDate} />
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
                        <Form.Item
                            name="unitId"
                            label=" Unit"
                            rules={[
                                {
                                    required: false, message: 'Select Unit',
                                },
                            ]}
                        >
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                placeholder="Select Unit"
                                allowClear
                                style={{ width: '100%' }}
                                // onChange={handleUnit}
                                // disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}

                            >
                                {unitData.map(dropData => {
                                    return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item
              name="product"
              label="Product SKU"
              rules={[
                {
                  required: false,
                  message: 'product is required'
                },
              ]}
            >
              <Select
                showSearch
                optionFilterProp="children"
                // filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Product SKU"
                // onChange={getSaleOrderItems}
                allowClear
                dropdownMatchSelectWidth={false}
              >
                {/* <Option value={''}>Please Select</Option> */}
                {productData?.map(productsku => {
                  return <Option key={productsku.varientId} value={productsku.varientId}>{productsku.shortCode}</Option>
                })}
              </Select>

            </Form.Item>
            
          </Col>
          {/* </Row>
          <Row justify='end'> */}
                    <Col style={{paddingRight:"12px"  }} >
                        <Button
                            type="primary"
                            onClick={() => getStockInTransactions()}
                            // style={{ width: 100 }}
                            // disabled={disable}
                        >
                            Get Report
                        </Button></Col>

                        <Col style={{  paddingLeft:'0px' }} >

                        <Button type="primary" htmlType="submit" onClick={onReset}  >
                            Reset
                        </Button>
                    </Col>


                </Row>
            </Form>
            <br />

            {   

                stockinTransactionsData.length > 0 ?
                    <>
                        {

                            stockinTransactionsData.forEach(item => {
                                totalReportedCases += Number(item.reportingCases);
                                totalLoosePouches+=Number(item.loosePouches)
                            })
                        }

                        {/* <Card title='Report Summary' extra={<Button icon={<FileExcelOutlined />} style={{ marginTop: 30, }} onClick={() => { exportExcel(); }}>
                                        Get Excel
                                    </Button>}> */}
                            <Row gutter={24}>
                                <Col>
                                    {/* <Statistic title="Total Transactions" value={stockinTransactionsData.length} /> */}
                                   <Card title={"Total Transactions: " + stockinTransactionsData.length} style={{ textAlign: 'left', width: 300, height: 41, backgroundColor: '#bfbfbf' }}></Card>
                                </Col>
                                <Col>
                                    {/* <Statistic title="Total Transactions" value={stockinTransactionsData.length} /> */}
                                   <Card title={"Total Reported Cases: " + totalReportedCases} style={{ textAlign: 'left', width: 300, height: 41, backgroundColor: '#bfbfbf' }}></Card>
                                </Col>
                                <Col>
                                    {/* <Statistic title="Total Transactions" value={stockinTransactionsData.length} /> */}
                                   <Card title={"Total Loose Pouches: " + totalLoosePouches} style={{ textAlign: 'left', width: 300, height: 41, backgroundColor: '#bfbfbf' }}></Card>
                                </Col>
                                {/* <Col span={4}>
                                    <Statistic title="Total Reported Cases" value={totalReportedCases} />
                                </Col> */}
                                {/* <Col span={4}>
                                    <Button icon={<FileExcelOutlined />} style={{ marginTop: 30}} onClick={() => { exportExcel(); }}>
                                        Get Excel
                                    </Button>
                                </Col> */}
                                {/* <Col>
                                    <Button icon={<FilePdfOutlined />} style={{ marginLeft: 20, marginTop: 30, }} onClick={() => { exportToPdf(); }}>
                                        Get PDF
                                    </Button>
                                </Col> */}
                                {/* <Col>
                                    <Button icon={<WhatsAppOutlined />} style={{ marginLeft: 20, marginTop: 30, }} onClick={() => { shareData() }}>
                                        Share
                                    </Button>
                                </Col> */}

                            </Row>
                            <br/>
                        {/* </Card> */}
                        <Table rowKey={record => record.stockId}
                            columns={columnsSkelton} dataSource={stockinTransactionsData}
                            pagination={{
                                pageSize: 100,
                                onChange(current, pageSize) {
                                    setPage(current);
                                    setPageSize(pageSize);
                                }
                            }}
                            // rowClassName={(record) => {
                            //     return record.antibioticTestResult == 1 ? "highlight-row" : "";
                            // }}
                            onRow={(record) => {
                            return {
                                style: {
                                backgroundColor: record.antibioticTestResult == 1 ? "#f6f8aa" : "inherit", 
                                },
                            };
                            }}
                            onChange={onChange}
                            scroll={{ x: 1800, y: 500 }}
                            size="small"
                            bordered
                            summary={(pageData) => {
                                let totalreportingCases = 0
                                pageData.forEach(({ reportingCases }) => {
                                    totalreportingCases += Number(reportingCases);


                                });

                                return (
                                    <>
                                        <Table.Summary.Row className='tableFooter'>
                                            <Table.Summary.Cell index={3} colSpan={3}><Text style={{ textAlign: 'end' }}></Text></Table.Summary.Cell>
                                            <Table.Summary.Cell index={10} colSpan={6} ><Text >Total</Text></Table.Summary.Cell>
                                            <Table.Summary.Cell index={11}><Text style={{ textAlign: 'end' }}>{totalreportingCases}</Text></Table.Summary.Cell>
                                            {/* <Table.Summary.Cell index={12}><Text style={{ textAlign: 'end' }}>{Math.round(totalQuantity)}</Text></Table.Summary.Cell> */}
                                        </Table.Summary.Row>
                                    </>
                                );
                            }
                            }
                        />
                    </> : ""

            }

            <Modal title='Share on WhatsApp' visible={visible} onCancel={onCancel}>
                <Form form={modalForm} layout={'vertical'} >
                    <Row gutter={24}>
                        <Col span={12}>
                            <Form.Item name='number'>
                                <Input placeholder='Phone Number' />
                            </Form.Item>
                        </Col>
                        <Col span={6}>
                            <Button type='primary' onClick={sendMessage} > Send</Button>
                        </Col>
                    </Row>
                </Form>

            </Modal>




        </Card>

    );
}

export default StockInTransactionsReport;
