// import { EmployeeTokenConsumptionReportModel, EmployeeTokenConsumptionReportRequest, FreebieModel, FreebiesMappingConsumptionService, FreebiesServices, SummaryReportModel, SummaryReportRequest } from '@cmg/shared-models-and-services';
import { FreebiesMappingConsumptionService, FreebiesServices } from "@gtpl/shared-services/canteen-management";

import { Button, Col, DatePicker, Form, Input, Row, Select, Table } from 'antd';
// import { DatePickerProps, RangePickerProps } from 'antd/lib/date-picker/interface';
import { ColumnProps } from 'antd/lib/table';
import { useEffect, useState } from 'react';
// import { AlertMessages } from '../common/alert-messages';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Excel } from "antd-table-saveas-excel";
import { IExcelColumn } from 'antd-table-saveas-excel/app';
import React from 'react';
import { SummaryReportModel, SummaryReportRequest } from "@gtpl/shared-models/canteen-management";
import { DatePickerProps, RangePickerProps } from "antd/lib/date-picker";
import { useForm } from "antd/lib/form/Form";

// const sampleData = require('./data1.json');
export interface SummaryReportGridProps { }

export function SummaryReportGrid(props: SummaryReportGridProps) {

    const { RangePicker } = DatePicker;
    const tokensService = new FreebiesMappingConsumptionService();
    const [tokensConsumptionData, setTokenConsumptionData] = useState<SummaryReportModel[]>([]);
    const [fromDate, setFromDate] = useState<string>();
    const [toDate, setToDate] = useState<string>();
    const [form] = Form.useForm()

    const getTokenConsumptionSummaryReportData = (fromDate: string, toDate: string) => {
        // if (!fromDate || !toDate) {
        //     return AlertMessages.getErrorMessage('Date selection is mandatory');
        // }
        const sumReq = new SummaryReportRequest(fromDate, toDate);
        console.log(sumReq)
        tokensService.getTokenConsumptionSummaryReport(sumReq).then(res => {
            if (!res.status) {
                AlertMessages.getErrorMessage(res.internalMessage);
                return false;
            }
            setTokenConsumptionData(res.data);
        }).catch(err => {
            AlertMessages.getErrorMessage("");
        });
    }

    // get all the distinct date headers of the all the records. so these headers can be applied to the table
    const getCategoryHeaders = (data: SummaryReportModel[]) => {
        const catHeaders = new Set<string>();
        data.forEach(rec => rec.categoryWiseConsumption.forEach(cat => {
            catHeaders.add(cat.freebieCategory);
        }))
        return Array.from(catHeaders);
    };

    const getCategoryWiseConsumptionMap = (data: SummaryReportModel[]) => {
        const categoryWiseConsMap = new Map<string, Map<string, number>>();
        data.forEach(rec => {
            if (!categoryWiseConsMap.has(rec.date)) {
                categoryWiseConsMap.set(rec.date, new Map<string, number>());
            }
            rec.categoryWiseConsumption.forEach(day => {
                categoryWiseConsMap.get(rec.date).set(day.freebieCategory, day.tokensConsumed);
            })
        });
        return categoryWiseConsMap;
    }

    let excelTitles: IExcelColumn[] = [];
    const renderReport = (data: SummaryReportModel[]) => {
        const catHeaders = getCategoryHeaders(data);
        const categoryWiseEmpConsumptionMap = getCategoryWiseConsumptionMap(data);
        excelTitles = [
            { title: "Date", dataIndex: "date" }
        ];

        const columns: ColumnProps<any>[] = [
            {
                title: 'Date',
                dataIndex: 'date',
                key: 'date',
                width: 150,
            }
        ];
        catHeaders.forEach(freebie => {
            columns.push(
                {
                    title: freebie,
                    key: freebie,
                    width: 150,
                    render: (value, record: any, index) => {
                        let val = 0;
                        record.categoryWiseConsumption.forEach(fb => {
                            if (val == 0)
                                val = fb.freebieCategory == freebie ? fb.tokensConsumed : 0;
                        });
                        return val;
                    }
                }
            );
            excelTitles.push({
                title: freebie, dataIndex: "", render: (value: any, record: any) => {
                    let val = 0;
                    record.categoryWiseConsumption.forEach(fb => {
                        if (val == 0)
                            val = fb.freebieCategory == freebie ? fb.tokensConsumed : 0;
                    });
                    return val;
                }
            });
        });
        columns.push(
            {
                title: 'Total',
                dataIndex: 'grandTotal',
                key: 'total',
                width: 150
            }
        );

        excelTitles.push({ title: "Total", dataIndex: "grandTotal" });

        return <Table columns={columns} bordered dataSource={data} />
    }

    const dateChange = (value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string) => {
        // console.log('Selected Time: ', value);
        // console.log('Formatted Selected Time: ', dateString);
        setToDate(dateString[1]);
        setFromDate(dateString[0]);
    }

    const downloadExcel = () => {
        if (tokensConsumptionData.length == 0) {
            return AlertMessages.getErrorMessage('Nothing to download');
        }
        const excel = new Excel();
        excel
            .addSheet("Summary Report")
            .addColumns(excelTitles)
            .addDataSource(tokensConsumptionData, {
                // str2Percent: true
            })
            .saveAs("EmpReport.xlsx");
    }

    const onReset = () =>{
      form.resetFields()
      setTokenConsumptionData([])
    }


    return (
        <Form form={form}>
            <Row gutter={22}>
                <Col span={6}>
                    <Form.Item name='date' label="Date" required={true}>
                        <RangePicker format="YYYY-MM-DD" 
                        onChange={dateChange}
                         />
                    </Form.Item>
                </Col>
                <br />
                <br />
                <Col span={3}>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" onClick={() => getTokenConsumptionSummaryReportData(fromDate, toDate)}>
                            Submit
                        </Button>
                    </Form.Item>
                </Col>
                <Col span={3}>
                    <Button onClick={onReset}>
                        Reset
                    </Button>
                </Col>
                <Col span={3}>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" onClick={downloadExcel}>
                            Export Excel
                        </Button>
                    </Form.Item>
                </Col>
            </Row>
            <div>
                {renderReport(tokensConsumptionData)}
            </div>
        </Form>
    );
}

export default SummaryReportGrid;