import { PoStockReq } from '@gtpl/shared-models/procurement-management';
import { PurchaseOrderService } from '@gtpl/shared-services/procurement';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, Form, Row, Select, Table } from 'antd';
import { Excel } from 'antd-table-saveas-excel';
import { ColumnsType } from 'antd/lib/table';
import React, { useEffect, useState } from 'react';

export function PackingStockReport() {
    const [page, setPage] = useState(1);
    const [reportData, setReportData] = useState<any[]>([]);
    const [itemSubDrop, setItemSubCat] = useState<any[]>([]);
    const [item, setItem] = useState<any[]>([]);
    const [poDrop, setPoDrop] = useState<any[]>([]);
    const service = new PurchaseOrderService();
    const [form] = Form.useForm();
    const { Option } = Select;
    const [disable, setDisable] = useState<boolean>(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 100,
    })
    
    useEffect(() => {
        getItemSubCatForPackingStock();
        getPoNumForPackingStock();
        getPackingStockData();
        getItemsForPackingStock()
        
    }, []);

    const getPackingStockData = () => {
        setDisable(true);
        const req = new PoStockReq();
        // req.unitId = Number(localStorage.getItem('unit_id'))
        req.itemSubcategoryId = form.getFieldValue('itemSubcategoryId');
        req.saleOrderId = form.getFieldValue('saleOrderId');
        req.itemId = form.getFieldValue('itemId')

        service.getPackingStockData(req).then((res) => {
            setDisable(false);
            if (res.data) {
                setReportData(res.data);
                // AlertMessages.getSuccessMessage(res.internalMessage);
            } else {
                setReportData([]);
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        });
    };

    // Fetch Item Sub Category for the dropdown
    const getItemSubCatForPackingStock = () => {
        service.getItemSubCatForPackingStock({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) => {
            if (res.data) {
                setItemSubCat(res.data);
                // AlertMessages.getSuccessMessage(res.internalMessage);
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        });
    };

    const getPoNumForPackingStock = () => {
        service.getPoNumForPackingStock({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) => {
            if (res.data) {
                setPoDrop(res.data);
                // AlertMessages.getSuccessMessage(res.internalMessage);
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        });
    };

    const getItemsForPackingStock = () => {
        service.getItemsForPackingStock({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) => {
            if (res.data) {
                setItem(res.data);
                // AlertMessages.getSuccessMessage(res.internalMessage);
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        });
    };

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

    const generateColumns = () => {
        if (reportData.length === 0) return [];
    
        const unitNames = Object.keys(reportData[0]).filter(key => key !== 'itemName' && key !== 'total' && key !== 'uomName' );
    
        const columns :any = [
            {
                title: '#Sno',
                key: 'sno',
                width: '50px',
                render: (_, __, index) => ((pagination.current - 1) * pagination.pageSize) + index + 1
            },
            {
                title: 'Item',
                dataIndex: 'itemName',
                key: 'itemName',  
                width: '300px',
            },
            
            ...unitNames.map((unitName) => ({
                title: unitName,
                dataIndex: unitName,
                key: unitName,  
                render: (value: any, record: any) => {
                    const quantity = parseFloat(value); 
                    return isNaN(quantity) ? "0" : quantity; 
                },
                align: "center" as 'center', 
            })),
            {
                title: 'Total',
                dataIndex: 'total',
                width:"150px",
                key: 'total',  
                render: (value: any) => {
                    const numericValue = parseFloat(value);
                    return !isNaN(numericValue) ? numericValue : '0'; 
                },
                align: 'right' as 'right',  
            },
            {
                title: 'Item UOM ',
                dataIndex: 'uomName',
                key: 'uomName',  
                width: '100px',
                render:(text,record)=>{
                    return record.uomName ? record.uomName : '-';
                  }
            },
        ];
    
        return columns;
    };

    const columns = generateColumns();


    const exportExcel = () => {
        if (columns.length === 0 || reportData.length === 0) {
            AlertMessages.getErrorMessage("No data available to export");
            return;
        }
    
        const excel = new Excel();
    
        // Modify the columns for Excel export (only include ColumnType, filter out ColumnGroupType)
        const excelColumns = columns
            .filter((col): col is any => 'dataIndex' in col) // Type narrowing to ensure it's ColumnType
            .map(col => ({
                title: typeof col.title === 'string' ? col.title : String(col.title), // Ensure title is a string
                dataIndex: col.dataIndex,
                key: col.key,
            }));

            const transformedReportData = reportData.map((item) => {
                const newItem = { ...item };
                for (const key in newItem) {
                    if (newItem[key] === null || newItem[key] === "") {
                        newItem[key] = "-"; // Replace empty or null values with "-"
                    }
                }
                return newItem;
            });
    
        // Export the Excel file
        excel
            .addSheet('PackingStockReport')
            .addColumns(excelColumns) // Using the modified columns
            .addDataSource(transformedReportData, { str2num: true }) // Adding data source
            .saveAs('packing-stock-report.xlsx'); // Saving the file
    };
    
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };



    return (
        <>
            <Card
                title={<span style={{ color: 'white' }}>Packing Stock Report</span>}
                style={{ textAlign: 'center' }}
                headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
                extra={<Button onClick={() => { exportExcel(); }}>Get Excel</Button>}
            />
            <Form form={form} layout={'vertical'} style={{ padding: '0px' }}>
                <Row gutter={[24, 24]}>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6}}>
                        <Form.Item name="itemId" label="Item Name">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
                                placeholder="Select Item Name"
                                allowClear
                                dropdownMatchSelectWidth={false}
                            >
                                {item.map(dropData => (
                                    <Option key={dropData.itemId} value={dropData.itemId}>
                                        {dropData.itemName}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 5}} xl={{ span: 5}}>
                        <Form.Item name="itemSubcategoryId" label="Item Sub Category">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
                                placeholder="Select Item Sub Category"
                                allowClear
                                dropdownMatchSelectWidth={false}
                            >
                                {itemSubDrop.map(dropData => (
                                    <Option key={dropData.itemSubcategoryId} value={dropData.itemSubcategoryId}>
                                        {dropData.itemSubCat}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 5 }} xl={{ span: 5}}>
                        <Form.Item name="saleOrderId" label="Customer PO">
                            <Select
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.children.toLowerCase().includes(input.toLowerCase())}
                                placeholder="Select Customer PO"
                                allowClear
                                dropdownMatchSelectWidth={false}
                            >
                                {poDrop.map(dropData => (
                                    <Option key={dropData.saleOrderId} value={dropData.saleOrderId}>
                                        {dropData.saleOrder}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col style={{ marginTop: 30 }} xs={24} md={5}>
                        <Button
                            type="primary"
                            block
                            onClick={getPackingStockData}
                            disabled={disable}
                            style={{ marginRight: 10, width: 100 }}
                        >
                            Get Report
                        </Button>
                        <Button type="primary" onClick={onReset}>
                            Reset
                        </Button>
                    </Col>
                </Row>
            </Form>
            <Table
                rowKey="itemName" 
                columns={columns}
                dataSource={reportData}
                scroll={{ x: true }}
                pagination={{
                    pageSize: pagination.pageSize,
                    current: pagination.current,
                    onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
                }}
                onChange={handleTableChange}
                size='small'
                bordered
            />
        </>
    );
}
