import { GradingService } from '@gtpl/shared-services/production';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Card, Row, Table, Col, Form, Button, DatePicker, Input, Select } from 'antd';
import { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useState,useRef} from 'react';
import { DownloadOutlined, SearchOutlined,UndoOutlined} from "@ant-design/icons";
import { BillNumberRequest } from '@gtpl/shared-models/production-management';
import Highlighter from "react-highlight-words";
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
import { GrnService } from '@gtpl/shared-services/procurement';



export const gradingSummaryReport = () => {
    const service = new GradingService();
    const [gradeData, setGradeData] = useState([]);
    const [page, setPage] = useState(1);
    const [form] = Form.useForm();
    const { RangePicker } = DatePicker;
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [lotNumbers,setLotNumbers] = useState([])
        const {Option}=Select;
        const loggedInUnitId = Number(localStorage.getItem('unit_id'));
        const [unitCodes, setUnitCodes] = useState([]);
        const grnService = new GrnService()



    

    useEffect(() => {
        getAllActiveGradingSummaryReport();
        getLogNumbersAgainistGradeRange()
    }, []);


        useEffect(() => {
          getAllUnits();
        }, []);
      
        const getAllUnits = () => {
          grnService.getUnitsForCeoDashboard().then((res) => {
            if (res.status) {
              setUnitCodes(res.data);
            }
          });
        };

    const getLogNumbersAgainistGradeRange =() =>{
        const req = new BillNumberRequest(undefined,undefined,undefined,undefined,undefined); 
        if (form.getFieldValue('date') !== undefined) {
            req.fromDate = (form.getFieldValue('date')[0]).format('YYYY-MM-DD');
          }
          if (form.getFieldValue('date') !== undefined) {
            req.toDate = (form.getFieldValue('date')[1]).format('YYYY-MM-DD');
          }
          if(loggedInUnitId === 5) {
            if (form.getFieldValue('unitId') !== undefined) {
              req.unitId = form.getFieldValue('unitId');
            }}else{
              req.unitId = loggedInUnitId; // Convert number to string
            }
          service.getLotNumbersAgainistGradeRange(req).then(res =>{
             if(res.status){
                setLotNumbers(res.data)
             }else{
                AlertMessages.getErrorMessage(res.internalMessage);

                setLotNumbers([])
             }
          }).catch((err) => {
            AlertMessages.getErrorMessage(err.message);
            setLotNumbers([]);
          });

    }
    const getAllActiveGradingSummaryReport = () => {
        const req = new BillNumberRequest(undefined,undefined,undefined,undefined,undefined); 
        if (form.getFieldValue('date') !== undefined) {
            req.fromDate = (form.getFieldValue('date')[0]).format('YYYY-MM-DD');
          }
          if (form.getFieldValue('date') !== undefined) {
            req.toDate = (form.getFieldValue('date')[1]).format('YYYY-MM-DD');
          }
          if(loggedInUnitId === 5) {
            if (form.getFieldValue('unitId') !== undefined) {
              req.unitId = form.getFieldValue('unitId');
            }}else{
              req.unitId = loggedInUnitId; // Convert number to string
            }
        service.getGradingSummaryReport(req).then(res => {
            if (res.status) {
                const processedData = res.data.map(item => {
                    const total = Object.keys(item).reduce((sum, key) => {
                        if (['8/12', '13/15', '16/20', '21/25', '26/30', '31/35', '36/40', '41/50', '51/60', '61/70', '71/90', '90/110', '100/120'].includes(key)) {
                            return sum + (parseFloat(item[key]) || 0);
                        }
                        return sum;
                    }, 0);

                    const yieldPercentage = item.honQuantity !== 0 ? ((total / item.honQuantity) * 100).toFixed(2) + '%' : '0%';

                    return {
                        ...item,
                        total,
                        yield: yieldPercentage
                    };
                });
                console.log(processedData,'processedData')
                setGradeData(processedData);
            } else {
                AlertMessages.getErrorMessage(res.internalMessage);
                setGradeData([]);
            }
        }).catch(err => {
            AlertMessages.getErrorMessage(err.message);
        });
    };
  
    function getLotRange(): string {
        if (lotNumbers.length === 0) return '';
    
        // Map through each record to extract the first and last lot numbers
        const lotRanges = lotNumbers.map(record => {
            const { first_lot_number, last_lot_number } = record;
            return `${first_lot_number} TO ${last_lot_number}`;
        });
    
        // Join the lot ranges with commas
        return lotRanges.join(' , ');
    }
    

    
    

    const calculateTotal = (data, key) => {
        return data.reduce((sum, item) => sum + (parseFloat(item[key]) || 0), 0);
    };

    // const getColumnSearchProps = (dataIndex: string) => ({
    //     filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
    //         <div style={{ padding: 8 }}>
    //             <Input
    //                 ref={searchInput}
    //                 placeholder={`Search ${dataIndex}`}
    //                 value={selectedKeys[0]}
    //                 onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
    //                 onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
    //                 style={{ width: 188, marginBottom: 8, display: 'block' }}
    //             />
    //             <Button
    //                 type="primary"
    //                 onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
    //                 icon={<SearchOutlined />}
    //                 size="small"
    //                 style={{ width: 90, marginRight: 8 }}
    //             >
    //                 Search
    //             </Button>
    //             <Button size="small" style={{ width: 90 }}
    //                 onClick={() => {
    //                     handleReset(clearFilters)
    //                     setSearchedColumn(dataIndex);
    //                     confirm({ closeDropdown: true });
    //                 }}>
    //                 Reset
    //             </Button>
    //         </div>
    //     ),
    //     filterIcon: filtered => (
    //         <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    //     ),
    //     onFilter: (value, record) =>
    //         record[dataIndex]
    //             ? record[dataIndex]
    //                 .toString()
    //                 .toLowerCase()
    //                 .includes(value.toLowerCase())
    //             : false,
    //     onFilterDropdownVisibleChange: visible => {
    //         if (visible) { setTimeout(() => searchInput.current.select()); }
    //     },
    //     render: text =>
    //         text ? (
    //             searchedColumn === dataIndex ? (
    //                 <Highlighter
    //                     highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
    //                     searchWords={[searchText]}
    //                     autoEscape
    //                     textToHighlight={text.toString()}
    //                 />
    //             ) : text
    //         )
    //             : null
    // })

    const gradeColumns: ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'id',
            width: '70px',
            responsive: ['md'],
            // align: 'right',
            render: (text, object, index) => (page - 1) * 10 + (index + 1),
        },
        
        {
            title: 'HonCount',
            key: 'count',
            dataIndex: 'honCount',
            width: '100px',
            responsive: ['md'],
           

        },
        {
            title: 'HON Quantity',
            key: 'honQuantity',
            dataIndex: 'honQuantity',
            width: '100px',
            responsive: ['md'],
           
        },
        {
            title: '8/12',
            key: '8/12',
            dataIndex: '8/12',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '13/15',
            key: '13/15',
            dataIndex: '13/15',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '16/20',
            key: '16/20',
            dataIndex: '16/20',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '21/25',
            key: '21/25',
            dataIndex: '21/25',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '26/30',
            key: '26/30',
            dataIndex: '26/30',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '31/35',
            key: '31/35',
            dataIndex: '31/35',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '36/40',
            key: '36/40',
            dataIndex: '36/40',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '41/50',
            key: '41/50',
            dataIndex: '41/50',
            width: '70px',
            responsive: ['md'],
              align: 'right',
        },
        {
            title: '51/60',
            key: '51/60',
            dataIndex: '51/60',
            width: '70px',
            responsive: ['md'],
              align: 'right',
        },
        {
            title: '61/70',
            key: '61/70',
            dataIndex: '61/70',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '71/90',
            key: '71/90',
            dataIndex: '71/90',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '91/110',
            key: '90/100',
            dataIndex: '90/110',
            width: '70px',
            responsive: ['md'],
            align: 'right',
        },
        {
            title: '100/200',
            key: '100/120',
            dataIndex: '100/120',
            width: '70px',
            responsive: ['md'],
              align: 'right',
        },
        {
            title: 'TOTAL',
            key: 'total',
            dataIndex: 'total',
            width: '70px',
            responsive: ['md'],
              align: 'right',
              render: (text) => (parseFloat(text) || 0).toFixed(2),
        },
        {
            title: 'Yield %',
            key: 'yield',
            dataIndex: 'yield',
            width: '70px',
            responsive: ['md'],
              align: 'right',
        }
    ];

    const subgradeColumns:ColumnProps<any>[]  = [
        {
            title: 'S No',
            key: 'id',
            width: '70px',
            responsive: ['md'],
            //   align: 'right',
            render: (text, object, index) => (page - 1) * 10 + (index + 1),
        },
       
        {
            title: 'HonCount',
            key: 'count',
            dataIndex: 'honCount',
            width: '100px',
            responsive: ['md'],
            align:"right"

         
        },
        {
            title: 'Total HON Wt',
            key: 'honQuantity',
            dataIndex: 'honQuantity',
            width: '100px',
            responsive: ['md'],
            align:"right",
            render: (text) => (text / 1000).toFixed(2),
         
        },
        {
            title: 'Total HLSO wt',
            key: 'total',
            dataIndex: 'total',
            width: '70px',
            responsive: ['md'],
              align: 'right',
            render: (text) => (text / 1000).toFixed(2),
        },
        {
            title: 'Achieved Yield %',
            key: 'yield',
            dataIndex: 'yield',
            width: '70px',
            responsive: ['md'],
              align: 'right',
        },
        {
            title: 'Standard Yield %',
            key: 'standardYield',
            dataIndex: 'standardYield',
            width: '70px',
            responsive: ['md'],
              align: 'right',
            render: (text,record) => {
                return(
                    Number(record.standardYield)
                )
            }
        },
        {
            title: ' Main %',
            key: 'percent',
            // dataIndex: 'percent',
            width: '70px',
            responsive: ['md'],
            align: 'right',
            render: (text, record) => {
                const totalHonQuantity = calculateTotal(gradeData, 'honQuantity');
                const mainPercentage = totalHonQuantity !== 0 ? ((record.honQuantity / totalHonQuantity) * 100).toFixed(2) : '0.00';
                return `${mainPercentage}%`;
            },
            
            },
        
    ];

    const onReset = () => {
        form.resetFields()

    }

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


   


    const gradeSummaryFooter = () => {
        const totalHonQuantity = calculateTotal(gradeData, 'honQuantity');
        const total8_12 = calculateTotal(gradeData, '8/12');
        const total13_15 = calculateTotal(gradeData, '13/15');
        const total16_20 = calculateTotal(gradeData, '16/20');
        const total21_25 = calculateTotal(gradeData, '21/25');
        const total26_30 = calculateTotal(gradeData, '26/30');
        const total31_35 = calculateTotal(gradeData, '31/35');
        const total31_40 = calculateTotal(gradeData, '36/40');
        const total41_50 = calculateTotal(gradeData, '41/50');
        const total51_60 = calculateTotal(gradeData, '51/60');
        const total61_70 = calculateTotal(gradeData, '61/70');
        const total71_90 = calculateTotal(gradeData, '71/90');
        const total91_110 = calculateTotal(gradeData, '90/110');
        const total100_200 = calculateTotal(gradeData, '100/120');
        const totalTotal = calculateTotal(gradeData, 'total');

        return (
            <Table.Summary.Row>
                <Table.Summary.Cell index={0}>Total</Table.Summary.Cell>
                <Table.Summary.Cell index={1} />
             

                <Table.Summary.Cell index={2}>{totalHonQuantity.toFixed(2)}</Table.Summary.Cell>

                <Table.Summary.Cell index={3}>{total8_12.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={4}>{total13_15.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={5}>{total16_20.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={6}>{total21_25.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={7}>{total26_30.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={8}>{total31_35.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={9}>{total31_40.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={10}>{total41_50.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={11}>{total51_60.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={12}>{total61_70.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={13}>{total71_90.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={14}>{total91_110.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={15}>{total100_200.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={16}>{totalTotal.toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={17}>{}</Table.Summary.Cell>

                <Table.Summary.Cell index={18} />
            </Table.Summary.Row>
        );
    };

    const subgradeSummaryFooter = () => {
        const totalHonQuantity = calculateTotal(gradeData, 'honQuantity');
        const total = calculateTotal(gradeData, 'total');

        return (
            <Table.Summary.Row>
                <Table.Summary.Cell index={0}></Table.Summary.Cell>
                <Table.Summary.Cell index={1} > Total</Table.Summary.Cell>
              
                <Table.Summary.Cell index={2}>{(totalHonQuantity / 1000).toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={3}>{(total / 1000).toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={4} >{((total/totalHonQuantity)*100).toFixed(2)}</Table.Summary.Cell>
                <Table.Summary.Cell index={5} />
                <Table.Summary.Cell index={6} >100%</Table.Summary.Cell>
            </Table.Summary.Row>
        );
    };

    const exportExcel = async () => {
        const workbook = new ExcelJS.Workbook();
        const worksheet1 = workbook.addWorksheet('Summary');
        const worksheet2 = workbook.addWorksheet('Subgrade Summary');
    
        // Add main heading for Worksheet 1
        const mainHeading = `HON TO HLSO YIELD ${`${new Date().toLocaleString('default', { month: 'short' })}-${new Date().getFullYear()}`}`;
        const titleRow = worksheet1.addRow([mainHeading]);
        worksheet1.mergeCells(titleRow.number, 1, titleRow.number, 17); // Merge across all columns
        titleRow.getCell(1).alignment = { horizontal: 'center', vertical: 'middle' };
        titleRow.getCell(1).font = { bold: true, size: 14 };
    
        // Add a row for the lot range below the heading
        const lotRange = getLotRange();
        const lotRangeRow = worksheet1.addRow([lotRange]);
        worksheet1.mergeCells(lotRangeRow.number, 1, lotRangeRow.number, 17); // Merge across all columns
        lotRangeRow.getCell(1).alignment = { horizontal: 'center', vertical: 'middle' };
        lotRangeRow.getCell(1).font = { italic: true, size: 12 }; // Optional: make it italic and smaller
    
        // Add a blank row for spacing
        worksheet1.addRow([]);
    
        // Define columns for the worksheet (these are the headers)
        worksheet1.columns = [
            { header: 'S No', key: 'sNo', width: 10 },
            { header: 'HonCount', key: 'honCount', width: 20 },
            { header: 'HON Quantity', key: 'honQuantity', width: 20 },
            { header: '8/12', key: '8/12', width: 10 },
            { header: '13/15', key: '13/15', width: 10 },
            { header: '16/20', key: '16/20', width: 10 },
            { header: '21/25', key: '21/25', width: 10 },
            { header: '26/30', key: '26/30', width: 10 },
            { header: '31/35', key: '31/35', width: 10 },
            { header: '36/40', key: '36/40', width: 10 },
            { header: '41/50', key: '41/50', width: 10 },
            { header: '51/60', key: '51/60', width: 10 },
            { header: '61/70', key: '61/70', width: 10 },
            { header: '71/90', key: '71/90', width: 10 },
            { header: '90/110', key: '90/110', width: 10 },
            { header: '100/200', key: '100/120', width: 10 },
            { header: 'Total', key: 'total', width: 10 },
            { header: 'Yield %', key: 'yield', width: 20 },
        ];
    
        // Add data rows (make sure this happens after column headers are set)
        gradeData.forEach((item, index) => {
            worksheet1.addRow({
                sNo: index + 1,
                ...item,
            });
        });
    
        // Calculate totals
        const totals = [
            'honQuantity', '8/12', '13/15', '16/20', '21/25', 
            '26/30', '31/35', '36/40', '41/50', '51/60', 
            '61/70', '71/90', '90/110', '100/120'
        ].reduce((acc, key) => {
            acc[key] = calculateTotal(gradeData, key).toFixed(2);
            return acc;
        }, {});
    
        const totalRow = {
            sNo: 'Total',
            ...totals,
            total: calculateTotal(gradeData, 'total').toFixed(2),
        };
        worksheet1.addRow(totalRow);
    
        // Set up worksheet2
        worksheet2.columns = [
            { header: 'S No', key: 'id', width: 10 },
            // { header: 'Lot Number', key: 'lot_number', width: 20 },
            { header: 'HonCount', key: 'honCount', width: 20 },
            { header: 'Total HON Wt', key: 'honQuantity', width: 20 },
            { header: 'Achieved Yield %', key: 'yield', width: 20 },
            { header: 'Standard Yield %', key: 'standardYield', width: 20 },
            { header: 'Main %', key: 'percent', width: 20 },
        ];
    
        // Add data rows for Worksheet 2
        gradeData.forEach((item, index) => {
              const totalHonQuantity = calculateTotal(gradeData, 'honQuantity');
                const mainPercentage = totalHonQuantity !== 0 ? ((item.honQuantity / totalHonQuantity) * 100).toFixed(2) : '0.00';
            worksheet2.addRow({
                id: index + 1,
                // lot_number: item.lot_number, // Ensure this key exists in your data
                honCount: item.honCount,
                honQuantity: item.honQuantity,
                yield: item.yield,
                standardYield : item.standardYield,
                percent : mainPercentage
                // Ensure you include 'standardYield' and 'percent' if they exist
            });
        });
    
        // Calculate totals for Worksheet 2
        const totalHonQuantity2 = calculateTotal(gradeData, 'honQuantity');
        const totalYield = calculateTotal(gradeData, 'yield');
    
        worksheet2.addRow({
            id: 'Total',
            honQuantity: (totalHonQuantity2 / 1000).toFixed(2),
            yield: (totalYield / 1000).toFixed(2),
        });
    
        // Save the Excel file
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], { type: 'application/octet-stream' });
        saveAs(blob, 'Grading_Summary_Report.xlsx');
    };
    
    
    
    return (
        <div>
            <Card size="small" title={<span style={{ color: 'white' }}>Grade Summary Report</span>}
                style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
                extra={
                    <div>
                      <Button icon={<DownloadOutlined />} onClick={() => { exportExcel(); }} style={{marginRight:30}}>
                        GET EXCEL
                      </Button></div>}>


                      <Form
  onFinish={() => {
    // Call both services and wait for them to complete
    Promise.all([getAllActiveGradingSummaryReport(), getLogNumbersAgainistGradeRange()])
      .then((results) => {
        // Handle success for both services
        const [gradingSummaryReport, logNumbersAgainstGradeRange] = results;
        console.log('Grading Summary Report:', gradingSummaryReport);
        console.log('Log Numbers Against Grade Range:', logNumbersAgainstGradeRange);
      })
      .catch((error) => {
        // Handle errors for either service
        console.error('Error occurred while fetching data:', error);
      });
  }}
  form={form}
  layout='vertical'
>
            <Row gutter={24}>
  

                <Col
                  xs={{ span: 24 }}
                  sm={{ span: 24 }}
                  md={{ span: 5 }}
                  lg={{ span: 5 }}
                  xl={{ span: 5 }}
                >
                  <Form.Item name="date"
                label="Date"
                     >
                <RangePicker  allowClear />
              </Form.Item>
                </Col>
   <Col
              xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 10 }}
              lg={{ span: 10 }}
              xl={{ span: 10 }}
            >
              <Form.Item name="unitId" label="Unit">
                <Select
                  placeholder="Select Unit"
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  allowClear
                  disabled={
                    Number(localStorage.getItem('unit_id')) != 5 ? true : false
                  }
                  defaultValue={
                    loggedInUnitId == 5
                      ? ''
                      : Number(localStorage.getItem('unit_id'))
                  }
                >
                  {unitCodes.map((dropData) => {
                    return (
                      <Option value={dropData.unitCodeId}>
                        {dropData.plantCode}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
               <Row>
              <Col
                xs={{ span: 24 }}
                sm={{ span: 24 }}
                md={{ span: 5 }}
                lg={{ span: 5 }}
                xl={{ span: 4 }}
                style={{marginTop:28,marginLeft:30}}
              >
                <Form.Item>
                  <Button
                    htmlType="submit"
                    icon={<SearchOutlined />}
                    type="primary"
                    // onClick={getPdfFileInfo}
                  >
                    Search
                  </Button>
                </Form.Item>
              </Col>
              <Col style={{ marginLeft: 70,marginTop:28}}>
                <Form.Item>
                  <Button
                    htmlType="submit"
                    onClick={onReset}
                    danger
                    icon={<UndoOutlined />}
                  >
                    Reset
                  </Button>
                </Form.Item>

              </Col>
            </Row>
            </Row>
    
    

            </Form>
            </Card>

            {gradeData.length > 0 && (
            <>

            <Card size='small'
                    title={<div > 
         {/* <u>HON TO HLSO YIELD {`${new Date().toLocaleString('default', { month: 'short' })}-${new Date().getFullYear()}`}</u>                      */}
         <u>
                    HON TO HLSO YIELD {`${form.getFieldValue('date')?.[0] 
                    ? new Date(form.getFieldValue('date')[0]).toLocaleString('default', { month: 'short' }) + '-' +
                    new Date(form.getFieldValue('date')[0]).getFullYear()
                    : new Date().toLocaleString('default', { month: 'short' }) + '-' + new Date().getFullYear()}`}
                </u>
                <div>{getLotRange()}</div>
                    </div>}
                    style={{ textAlign: 'center' }} 
            ></Card>
            <Table
                    columns={gradeColumns}
                    dataSource={gradeData}
                    pagination={{ pageSize: 10, current: page, onChange: page => setPage(page) }}
                    summary={gradeSummaryFooter}
                    scroll={{ x: true }} /><Row justify="center" gutter={16}>
                        <Col span={12}>
                        <Card size='small'
                    title={<div > 
         {/* <u>HON TO HLSO YIELD {`${new Date().toLocaleString('default', { month: 'short' })}-${new Date().getFullYear()}`}</u>                      */}
         <u>
                    HON TO HLSO YIELD {`${form.getFieldValue('date')?.[0] 
                    ? new Date(form.getFieldValue('date')[0]).toLocaleString('default', { month: 'short' }) + '-' +
                    new Date(form.getFieldValue('date')[0]).getFullYear()
                    : new Date().toLocaleString('default', { month: 'short' }) + '-' + new Date().getFullYear()}`}
                </u>
                <div>{getLotRange()}</div>
                    </div>}
                    style={{ textAlign: 'center' }} 
            ></Card>
                            <Table
                                columns={subgradeColumns}
                                dataSource={gradeData}
                                scroll={{ x: true }}
                                pagination={false}
                                summary={subgradeSummaryFooter} />
                        </Col>
                    </Row></>
              )} 
        </div>
    );
};

export default gradingSummaryReport;
