import { StockSTatementReq } from "@gtpl/shared-models/warehouse-management"
import { WarehouseDashboardService } from "@gtpl/shared-services/analytics"
import { Button, Card, Col, DatePicker, Form, message, Row, Select, Table } from "antd"
import { Excel } from "antd-table-saveas-excel"
import React, { useEffect, useState } from "react"
import {UndoOutlined} from '@ant-design/icons'
import moment from "moment"
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { PurchasesProductService } from '@gtpl/shared-services/finance';

// import { ColumnProps, ColumnsType } from "antd/lib/table"
import { ColumnsType } from 'antd/es/table'

    // Define interface for column object
    interface Column {
        title: string;
        dataIndex: string;
        key: string;
      }

export const StockStatementReport = () => {
    const [fgData,setFgData] = useState<any>([])
    const service = new WarehouseDashboardService()
    const [form] = Form.useForm()
    const [fggrades,setFgGrades] = useState<any[]>([])
    const [jumblegrades,setJumbleGrades] = useState<any[]>([])
    const [g2grades,setG2Grades] = useState<any[]>([])
    const [otherProductgrades,setOtherProductGrades] = useState<any[]>([])
    const [jumbleData,setJumbleData] = useState<any>([])
    const [g2Data,setG2Data] = useState<any>([])
    const [otherProductsData,setOtherProductsData] = useState<any>([])
    const [data,setData] = useState<any>([])
    const monthNames = ["JAN","FEB","MARCH","APRIL","MAY","JUNE","JULY","AUG","SEP","OCT","NOV","DEC"];
    const [month,setMonth] = useState<string>('')
    const [year,setYear] = useState<number>()
    const [date,setDate] = useState<number>()
    const [unitCodes,setUnitCodes]=useState([])
    const {Option}=Select;
    const role = JSON.parse(localStorage.getItem('role')) 
    const purchaseService = new PurchasesProductService()


    useEffect(() => {
        const allfggrades = Array.from(new Set(fgData.flatMap(item => item.gradesInfo.map(info => info.grade))));
        setFgGrades(allfggrades)
    },[fgData])

    useEffect(() => {
        const alljumblegrades = Array.from(new Set(jumbleData.flatMap(item => item.gradesInfo.map(info => info.grade))));
        setJumbleGrades(alljumblegrades)
    },[jumbleData])

    useEffect(() => {
        const allg2grades = Array.from(new Set(g2Data.flatMap(item => item.gradesInfo.map(info => info.grade))));
        setG2Grades(allg2grades)
    },[g2Data])

    useEffect(() => {
        const allotherProductsgrades = Array.from(new Set(otherProductsData.flatMap(item => item.gradesInfo.map(info => info.grade))));
        setOtherProductGrades(allotherProductsgrades)
    },[otherProductsData])

    useEffect(()=>{
        getAllUnits()            
    },[])

    const getAllUnits = () => {
        purchaseService.getAllUnits().then((res) => {
            if (res.status) {
                setUnitCodes(res.data)
            }
        })
    }

    const getData = () => {
        const selectedDate = form.getFieldValue('date');
        const date = selectedDate ? moment(selectedDate).format('YYYY-MM-DD') : null;
        if(date==="null"){
            message.error("Date Is Required")
        }
        const inputDate = new Date(date)
        const year = inputDate.getFullYear();
        const month = String(inputDate.getMonth() + 1).padStart(2, '0');
        const day = String(inputDate.getDate()).padStart(2, '0');
        setYear(year)
        setDate(Number(day))
        setMonth(monthNames[Number(month) -1])
        const req = new StockSTatementReq(date)
        const selectedUnitIds = form.getFieldValue('unitId');
        if (selectedUnitIds && selectedUnitIds.length > 0) {
            req.plantId = selectedUnitIds; // Only set if there's a valid array of selected units
        }
        //   const loggedInRole = JSON.parse(localStorage.getItem('role'));
        //   const loggedInUnitId = Number(localStorage.getItem('unit_id'));
      
        //   if (loggedInRole !== 'SUPERADMIN') {
        //     req.plantId = loggedInUnitId 
        // } 
        service.getStockStatementInfo(req).then(res => {
            console.log(req, "req frontend");
            if (res.status) {
                const { fgInfo, jumbleInfo, g2Info, otherProdutsInfo } = res.data;
        
                if (fgInfo.length === 0 && jumbleInfo.length === 0 && g2Info.length === 0 && otherProdutsInfo.length === 0) {
                    AlertMessages.getErrorMessage("No Data Found");
                    setData([]); // Clear the table
                    setFgData([]);
                    setJumbleData([]);
                    setG2Data([]);
                    setOtherProductsData([]);
                } else {
                    // Set data if at least one array has values
                    setData(res.data);
                    setFgData(fgInfo);
                    setJumbleData(jumbleInfo);
                    setG2Data(g2Info);
                    setOtherProductsData(otherProdutsInfo);
                }
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
            }
        });
        
    }

    const updateProductionCostAnalysis = () =>{
        service.updateProductionCostAnalysis().then(res=>{
            if (res.status){
                // AlertMessages.getSuccessMessage(res.internalMessage)
                getData()
            } else {
                AlertMessages.getErrorMessage(res.internalMessage)
            }
        })
    }


    const exportExcel = () => {
        const excel = new Excel();
        excel
          .addSheet('Stock-Statement-Report')
          .addColumns([])
          .addDataSource(fgData, { str2num: true })
          .saveAs('StockStatementReport.xlsx');
      }
    
      const onSearch = async () => {
        try {
          await form.validateFields(); // Validate required fields before proceeding
      
          // If validation passes, reset data and call the service
          setData([]);
          setFgData([]);
          setJumbleData([]);
          setG2Data([]);
          setOtherProductsData([]);
          updateProductionCostAnalysis();
        } catch (error) {
          console.log("Validation failed:", error);
          // The form will automatically show validation errors (like "Missing Date")
        }
      };
      

      const onReset = () => {
        form.resetFields()
        setData([])
        setFgData([])
        setJumbleData([])
        setG2Data([])
        setOtherProductsData([])
      }

    return(
        <>
            <style>
                {
                    `
                    .download-table-xls-button{
                       padding:3px;
                    }
                    `
                }
            </style>
            <Card size='small' title={<span style={{color:'white'}}>Stock Statement</span>} 
                extra={
                <ReactHTMLTableToExcel
                    id="excel-button"
                    className="download-table-xls-button"
                    table="fg-table"
                    filename="Stock Statement"
                    sheet="Sheet 1"
                    buttonText="Get Excel"
                />
                }
            style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} 
            // extra={fgData?.length > 0 ? (<><Button onClick={() => exportExcel()}>Get Excel</Button></>) : (<></>)}
            >
                <Form form={form}>
                    <Row gutter={24}>
                        <Col span={5}>
                        <Form.Item label='Date' name='date' rules={[{ required: true, message: 'Missing Date' }]}>
                        <DatePicker style={{width:'100%'}} placeholder="Select Date"/>
                        </Form.Item>
                        </Col>
                        <Col span={8}>
                        <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
                                mode="multiple"
                                // 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  span={3}>
                        <Form.Item>
                            <Button onClick={onSearch} type="primary">Get Report</Button>
                        </Form.Item>
                        </Col>
                        <Col  span={3}>
                        <Form.Item >
                            <Button icon={<UndoOutlined/>} type="primary" onClick={onReset}>Reset</Button>
                        </Form.Item>
                        </Col>
                    </Row>
                    
                    
                </Form>
                {/* <Table dataSource={tableData} columns={columns} /> */}
                {
                    fgData.length > 0 || jumbleData.length > 0 || g2Data.length > 0 || otherProductsData.length > 0 ? (<>
                    
                    <div>
                    {/* <ReactHTMLTableToExcel
                            id='excel-button'
                            className='download-table-xls-button'
                            table='fg-table'
                            filename='fgTablexls'
                            sheet="Sheet 1"
                            buttonText='Get Excel'
                    /> */}
                    <table id='fg-table' width='100%'>
                        <h3  
                        style={{margin:'0px'}}
                        >{`STOCK STATEMENT AS ON ${date}-${month}-${year}`}</h3>
                    
                        {
                            fgData.length > 0 ? ( 
                            <>
                            <h4 
                            style={{backgroundColor:'#72b5b0'}}
                            >FG PRODUCTS</h4>
                        
                            <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}} >
                                <tr style={{backgroundColor:'#36BA98'}}>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>Grade</th>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>UOM</th>
                                    {
                                        fggrades.map(rec => {
                                            return(
                                                <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>{rec}</th>
                                            )
                                        })
                                    }
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>Total</th>
                                </tr>
                                {
                                    fgData.map((rec,index) => {
                                        let totalCartons = 0
                                        let totalLoosePouches = 0
                                        return(
                                            // <tr>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>{rec.product}</td>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}} colSpan={fggrades.length + 2}>
                                            //         <table width={'100%'}>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderLeft:'none'}}>M/C</td>
                                            //                 {
                                            //                     fggrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderRight:'none'}}>{totalCartons}</td>
                                                            
                                            //             </tr>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderLeft:'none',borderBottom:'none'}}>Loose</td>
                                            //                 {
                                            //                     fggrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none'}}>{countInfo ? countInfo.loosePouches : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none',borderRight:'none'}}>{totalLoosePouches}</td>
                                            //             </tr>
                                            //         </table>
                                            //     </td>
                                            // </tr>
                                            <React.Fragment>
                                            <tr>
                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',fontWeight:500,backgroundColor:'#dfdede'}} rowSpan={2}>{rec.product}</td>                                             
                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>M/C</td>
                                                {
                                                    fggrades.map(grade => {
                                                        const countInfo = rec.gradesInfo.find(e => {
                                                            return(e.grade == grade)
                                                        })
                                                        totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                                        return(
                                                            <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                                        )
                                                    })
                                                }
                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalCartons).toFixed(2))}</td>

                                            </tr>
                                            <tr>
                                            <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Loose</td>
                                            {
                                                fggrades.map(grade => {
                                                    const countInfo = rec.gradesInfo.find(e => {
                                                        return(e.grade == grade)
                                                    })
                                                    totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                                    return(
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? Number(countInfo.loosePouches) : 0}</td>
                                                    )
                                                })
                                            }
                                            <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalLoosePouches).toFixed(2))}</td>
                                        </tr>
                                        </React.Fragment>
                                        )
                                    })
                                }
                            </table></>) : (<></>)
                        }
                        <br/>
                        {
                            jumbleData.length > 0 ? (<>
                            <h4 style={{backgroundColor:'#72b5b0'}}>JUMBLE PRODUCTS</h4>
                            <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}} id='fg-table'>
                                <tr style={{backgroundColor:'#36BA98'}}>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>Grade</th>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>UOM</th>
                                    {
                                        jumblegrades.map(rec => {
                                            return(
                                                <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>{rec}</th>
                                            )
                                        })
                                    }
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>Total</th>
                                </tr>
                                {
                                    jumbleData.map((rec,index) => {
                                        let totalCartons = 0
                                        let totalLoosePouches = 0
                                        return(
                                            // <tr>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>{rec.product}</td>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}} colSpan={jumblegrades.length + 2}>
                                            //         <table width={'100%'}>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderLeft:'none'}}>M/C</td>
                                            //                 {
                                            //                     jumblegrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderRight:'none'}}>{totalCartons}</td>
                                            //             </tr>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderLeft:'none',borderBottom:'none'}}>Loose</td>
                                            //                 {
                                            //                     jumblegrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none'}}>{countInfo ? countInfo.loosePouches : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none',borderRight:'none'}}>{totalLoosePouches}</td>
                                            //             </tr>
                                            //         </table>
                                            //     </td>
                                            // </tr>
                                            <React.Fragment>
                                                <tr>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#dfdede',fontWeight:500}} rowSpan={2}>{rec.product}</td>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>M/C</td>
                                                    {
                                                        jumblegrades.map(grade => {
                                                            const countInfo = rec.gradesInfo.find(e => {
                                                                return(e.grade == grade)
                                                            })
                                                            totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                                            return(
                                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                                            )
                                                        })
                                                    }
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalCartons).toFixed(2))}</td>
                                                </tr>
                                                <tr>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Loose</td>
                                                    {
                                                        jumblegrades.map(grade => {
                                                            const countInfo = rec.gradesInfo.find(e => {
                                                                return(e.grade == grade)
                                                            })
                                                            totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                                            return(
                                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? Number(countInfo.loosePouches) : 0}</td>
                                                            )
                                                        })
                                                    }
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalLoosePouches).toFixed(2))}</td>
                                                </tr>
                                            </React.Fragment>
                                        )
                                    })
                                }
                            </table>
                            </>) : (<></>)
                        }
                        <br/>
                        {
                            g2Data.length > 0 ? (<>
                                <h4 style={{backgroundColor:'#72b5b0'}}>GII/DC/BKN PRODUCTS</h4>
                                <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}}>
                                    <tr style={{backgroundColor:'#36BA98'}}>
                                        <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>Grade</th>
                                        <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>UOM</th>
                                        {
                                            g2grades.map(rec => {
                                                return(
                                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>{rec}</th>
                                                )
                                            })
                                        }
                                        <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>Total</th>
                                    </tr>
                                    {
                                        g2Data.map((rec,index) => {
                                            let totalCartons = 0
                                            let totalLoosePouches = 0
                                            return(
                                                // <tr>
                                                //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>{rec.product}</td>
                                                //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}} colSpan={g2grades.length + 2}>
                                                //         <table width={'100%'}>
                                                //             <tr>
                                                //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderLeft:'none'}}>M/C</td>
                                                //                 {
                                                //                     g2grades.map(grade => {
                                                //                         const countInfo = rec.gradesInfo.find(e => {
                                                //                             return(e.grade == grade)
                                                //                         })
                                                //                         totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                                //                         return(
                                                //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                                //                         )
                                                //                     })
                                                //                 }
                                                //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderRight:'none'}}>{totalCartons}</td>
                                                //             </tr>
                                                //             <tr>
                                                //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderLeft:'none',borderBottom:'none'}}>Loose</td>
                                                //                 {
                                                //                     g2grades.map(grade => {
                                                //                         const countInfo = rec.gradesInfo.find(e => {
                                                //                             return(e.grade == grade)
                                                //                         })
                                                //                         totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                                //                         return(
                                                //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none',borderRight:'none'}}>{countInfo ? countInfo.loosePouches : 0}</td>
                                                //                         )
                                                //                     })
                                                //                 }
                                                //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none',borderRight:'none'}}>{totalLoosePouches}</td>
                                                //             </tr>
                                                //         </table>
                                                //     </td>
                                                // </tr>
                                                <React.Fragment>
                                                    <tr>
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#dfdede',fontWeight:500}} rowSpan={2}>{rec.product}</td>
                                                            
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>M/C</td>
                                                        {
                                                            g2grades.map(grade => {
                                                                const countInfo = rec.gradesInfo.find(e => {
                                                                    return(e.grade == grade)
                                                                })
                                                                totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                                                return(
                                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                                                )
                                                            })
                                                        }
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalCartons).toFixed(2))}</td>
                                                    </tr>
                                                    <tr>
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Loose</td>
                                                        {
                                                            g2grades.map(grade => {
                                                                const countInfo = rec.gradesInfo.find(e => {
                                                                    return(e.grade == grade)
                                                                })
                                                                totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                                                return(
                                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? Number(countInfo.loosePouches) : 0}</td>
                                                                )
                                                            })
                                                        }
                                                        <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalLoosePouches).toFixed(2))}</td>
                                                    </tr>
                                                
                                                </React.Fragment>
                                            )
                                        })
                                    }
                                </table>
                            </>) : (<></>)
                        }
                        <br/>
                        
                        {
                            otherProductsData?.length > 0 ? ( 
                            <>
                            <h4 style={{backgroundColor:'#72b5b0'}}>OTHER PRODUCTS</h4>
                        
                            <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}} >
                                <tr style={{backgroundColor:'#36BA98'}}>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>Grade</th>
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>UOM</th>
                                    {
                                        otherProductgrades.map(rec => {
                                            return(
                                                <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>{rec}</th>
                                            )
                                        })
                                    }
                                    <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px'}}>Total</th>
                                </tr>
                                {
                                    otherProductsData.map((rec,index) => {
                                        let totalCartons = 0
                                        let totalLoosePouches = 0
                                        return(
                                            // <tr>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'300px'}}>{rec.product}</td>
                                            //     <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}} colSpan={otherProductgrades.length + 2}>
                                            //         <table width={'100%'}>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderLeft:'none'}}>M/C</td>
                                            //                 {
                                            //                     otherProductgrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderTop:'none',borderRight:'none'}}>{totalCartons}</td>
                                                            
                                            //             </tr>
                                            //             <tr>
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderLeft:'none',borderBottom:'none'}}>Loose</td>
                                            //                 {
                                            //                     otherProductgrades.map(grade => {
                                            //                         const countInfo = rec.gradesInfo.find(e => {
                                            //                             return(e.grade == grade)
                                            //                         })
                                            //                         totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                            //                         return(
                                            //                             <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none'}}>{countInfo ? countInfo.loosePouches : 0}</td>
                                            //                         )
                                            //                     })
                                            //                 }
                                            //                 <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',width:'150px',borderBottom:'none',borderRight:'none'}}>{totalLoosePouches}</td>
                                            //             </tr>
                                            //         </table>
                                            //     </td>
                                            // </tr>
                                            <React.Fragment>
                                                <tr>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#dfdede',fontWeight:500}} rowSpan={2}>{rec.product}</td>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>M/C</td>
                                                    {
                                                        otherProductgrades.map(grade => {
                                                            const countInfo = rec.gradesInfo.find(e => {
                                                                return(e.grade == grade)
                                                            })
                                                            totalCartons = totalCartons + (countInfo ? Number(countInfo.masterCartons) : 0)
                                                            return(
                                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{countInfo ? countInfo.masterCartons : 0}</td>
                                                            )
                                                        })
                                                    }
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{Number(Number(totalCartons).toFixed(2))}</td>
                                                            
                                                </tr>
                                                <tr>
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Loose</td>
                                                    {
                                                        otherProductgrades.map(grade => {
                                                            const countInfo = rec.gradesInfo.find(e => {
                                                                return(e.grade == grade)
                                                            })
                                                            totalLoosePouches = totalLoosePouches + (countInfo ? Number(countInfo.loosePouches) : 0)
                                                            return(
                                                                <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#d8f3dc'}}>{countInfo ? Number(countInfo.loosePouches) : 0}</td>
                                                            )
                                                        })
                                                    }
                                                    <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#d8f3dc'}}>{Number(Number(totalLoosePouches).toFixed(2))}</td>
                                                </tr>
                                            </React.Fragment>
                                        )
                                    })
                                }
                            </table></>) : (<></>)
                        }
                        <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}}>
                            <tr>
                                <td  style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#f4e2d0'}}><b>Total Stock Qty In Kgs</b></td>
                                <td  style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#f4e2d0'}}><b>{data.totalQtyInKgs}</b></td>
                            </tr>
                            <tr>
                                <td  style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#B6A28E'}}><b> {`Production As Of ${month}'${year} In Kgs`}</b></td>
                                <td  style={{textAlign:'center',fontSize:'15px',border:'1px solid black',backgroundColor:'#B6A28E'}}><b>{data.totalProduction}</b></td>
                            </tr>
                        </table>

                    </table>
                    </div>
                   
                    </>) : (<></>)
                }
                

                
            </Card>
        </>

    )
}

export default StockStatementReport
