
// import { DailySheetData } from '@gtpl/shared-models/common-models';
// import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
// import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
// import { Button, Card, Col, DatePicker, Form, Input, Row, Table } from 'antd';
// import Highlighter from 'react-highlight-words';
// import { DownloadOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
// import { Excel } from 'antd-table-saveas-excel';



// import { ColumnsType } from 'antd/lib/table';
// import React, { useEffect, useRef, useState } from 'react';
// import moment from 'moment';

// export function WhatsAppUsageReport() {
//     const [form] = Form.useForm();
//     const [usageData, setUsageData] = useState<any[]>([]);
//     const [searchText, setSearchText] = useState('');
//     const [searchedColumn, setSearchedColumn] = useState('');

//     const [object, setObject] = useState(null);
//     const searchInput = useRef(null);
//     const { RangePicker } = DatePicker;



//     const services = new ContainerRegisterService();

//     useEffect(() => {
//         getUsageData();
//     }, []);

//     const getUsageData = () => {
//     const defaultFromDate = moment().format("YYYY-MM-DD");
//     const defaultToDate = moment().format("YYYY-MM-DD");

//     const req = new DailySheetData(undefined,defaultFromDate, defaultToDate);

//     const dateRange = form.getFieldValue("dateRange");
//     if (dateRange !== undefined && dateRange.length === 2) {
//         req.fromDate = dateRange[0].format("YYYY-MM-DD");
//         req.toDate = dateRange[1].format("YYYY-MM-DD");
//     }
//         services.getDailySheetData1(req)
//             .then((res) => {
//                 if (res.status && res.data) {
//                     // Convert response data into a format suitable for the table
//                     const formattedData = Object.entries(res.data).map(([key, value]) => ({
//                         module: key,
//                         count: value,
//                     }));
//                     setUsageData(formattedData);
//                 } else {
//                     setUsageData([]);
//                 }
//             })
//             .catch((err) => {
//                 AlertMessages.getErrorMessage(err.message);
//                 setUsageData([]);
//             });
//     };

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

//     });

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

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

//     const columns: ColumnsType<any> = [
//         {
//             title: 'Module',
//             dataIndex: 'module',
//             key: 'module',
//             width: '40px',
//             sorter: (a: any, b: any) => a.module.localeCompare(b.module),
//             ...getColumnSearchProps('module'),


//         },
//         {
//             title: 'Count',
//             dataIndex: 'count',
//             key: 'count',
//             align: 'center',
//             width: '40px',
//             sorter: (a: any, b: any) => a.count - b.count,
//             //   ...getColumnSearchProps('count')

//         },
//     ];

//     const excelcolumns:any = [
//         {
//             title: 'Module',
//             dataIndex: 'module',
       
//         },
//         {
//             title: 'Count',
//             dataIndex: 'count',
    
//         },
//     ];

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

//     const exportExcel = () => {
//         const excel = new Excel();
//         excel
//           .addSheet('Usage Report')
//           .addColumns(excelcolumns)
//           .addDataSource(usageData, { str2num: true })
//           .saveAs('usageReport.xlsx');
//       }

//     return (
//         <Card
//             title={<span style={{ color: 'white' }}>Usage Report</span>}
//             style={{ textAlign: 'center' }}
//             headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
//             size="small"
//             extra={usageData.length > 0 && (
//                 <Button icon={<DownloadOutlined />} onClick={() => exportExcel()}>
//                   GET EXCEL
//                 </Button>
//               )}
//         >
//             <Form form={form} layout="vertical" style={{ padding: '0px' }} onFinish={getUsageData}>
//                 <Row gutter={24}>
//                     {/* <Col span={4}>

//                         <Form.Item name="date" label="Date" >
//                             <DatePicker  disabledDate={(current) => current && current > moment().endOf('day')} defaultValue={moment()} />
//                         </Form.Item>
//                     </Col> */}

//                     <Col
//                   xs={{ span: 24 }}
//                   sm={{ span: 24 }}
//                   md={{ span: 6 }}
//                   lg={{ span: 6 }}
//                   xl={{ span: 6 }}
//                 >
//                 <Form.Item name="dateRange"
//                 label="Date"
//                      >
//                 <RangePicker
//                     allowClear
//                     disabledDate={(current) => current && current > moment().endOf('day')}
//                     defaultValue={[moment(), moment()]} // Default range for today
//                     format="YYYY-MM-DD" // Optional: Ensure correct format
//                     />
//               </Form.Item>
//                 </Col>
//                     <Col span={4}>

//                         <Form.Item style={{marginTop:"27px"}}>
//                             <Button
//                                 htmlType="submit"
//                                 icon={<SearchOutlined />}
//                                 type="primary"
//                             >
//                                 Search
//                             </Button>
//                         </Form.Item>
//                     </Col>
//                     <Col span={4}>
//                     <Form.Item style={{marginTop:"27px",marginRight:'100px'}}>
//                             <Button
//                                 htmlType="reset"
//                                 onClick={onReset}
//                                 danger
//                                 icon={<UndoOutlined />}
//                             >
//                                 Reset
//                             </Button>
//                         </Form.Item>

//                     </Col>

//                 </Row>

//             </Form>
//             <Table
//                 columns={columns}
//                 dataSource={usageData}
//                 rowKey="type"
//                 pagination={false}
//                 bordered
//             />
//         </Card>
//     );
// }

// export default WhatsAppUsageReport;


import { DailySheetData } from '@gtpl/shared-models/common-models';
import { ContainerRegisterService } from '@gtpl/shared-services/logistics';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, DatePicker, Form, Input, Row, Table } from 'antd';
import Highlighter from 'react-highlight-words';
import { DownloadOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import { Excel } from 'antd-table-saveas-excel';
import { ColumnsType } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react';
import moment from 'moment';
import ExcelJS from "exceljs";
import { saveAs } from "file-saver";

export function WhatsAppUsageReport() {
    const [form] = Form.useForm();
    const [usageData, setUsageData] = useState<any[]>([]);
    const [columns, setColumns] = useState<any>([]);
    const searchInput = useRef(null);
    const { RangePicker } = DatePicker;
    const services = new ContainerRegisterService();
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const [object, setObject] = useState(null);

    useEffect(() => {
        getUsageData();
    }, []);

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

    });

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

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

    const getUsageData = () => {
        const defaultFromDate = moment().format("YYYY-MM-DD");
        const defaultToDate = moment().format("YYYY-MM-DD");

        const req = new DailySheetData(undefined, defaultFromDate, defaultToDate);

        const dateRange = form.getFieldValue("dateRange");
        if (dateRange && dateRange.length === 2) {
            req.fromDate = dateRange[0].format("YYYY-MM-DD");
            req.toDate = dateRange[1].format("YYYY-MM-DD");
        }

        services.getDailySheetData1(req)
            .then((res) => {
                if (res.status && res.data) {
                    const formattedData = transformData(res.data);
                    setUsageData(formattedData.data);
                    setColumns(formattedData.columns);
                } else {
                    setUsageData([]);
                    setColumns([]);
                }
            })
            .catch((err) => {
                AlertMessages.getErrorMessage(err.message);
                setUsageData([]);
            });
    };

    // const transformData = (rawData) => {
    //     const modules = Object.keys(rawData);
    //     const dates = Object.keys(rawData[modules[0]] || {});

    //     const dynamicColumns = [
    //         {
    //             title: 'Module',
    //             dataIndex: 'module',
    //             width:"250px",
    //             key: 'module',
    //             fixed: 'left',
    //             sorter: (a, b) => a.module.localeCompare(b.module),
    //            ...getColumnSearchProps('module'),

    //         },
    //         ...dates.map(date => ({
    //             title: date,
    //             dataIndex: date,
    //             key: date,
    //             align: 'center',
    //             sorter: (a, b) => (a[date] || 0) - (b[date] || 0),
    //             render: (value) => (
    //                 <span style={{ color: value === 0 ? 'red' : value > 5 ? 'green' : 'black' }}>
    //                     {value}
    //                 </span>
    //             ),
    //         })),
    //         {
    //             title: 'Total',
    //             dataIndex: 'total',
    //             key: 'total',
    //             align: 'center',
    //             sorter: (a, b) => a.total - b.total,
    //             fixed: 'right',
    //             render: (value) => (
    //                 <span style={{ color: value === 0 ? 'red' : value > 5 ? 'green' : 'black' }}>
    //                     {value}
    //                 </span>
    //             ),
    //         }
    //     ];

    //     const data = modules.map(module => {
    //         let row = { module };
    //         let total = 0;
    //         dates.forEach(date => {
    //             row[date] = rawData[module][date] || 0;
    //             total += row[date];
    //         });
    //         row['total'] = total;
    //         return row;
    //     });

    //     return { data, columns: dynamicColumns };
    // };

    // const exportExcel = () => {
    //     const excel = new Excel();
    //     excel
    //         .addSheet('Usage Report')
    //         .addColumns(columns.map(col => ({ title: col.title, dataIndex: col.dataIndex })))
    //         .addDataSource(usageData, { str2num: true })
    //         .saveAs('UsageReport.xlsx');
    // };




    // const transformData = (rawData) => {
    //     const modules = Object.keys(rawData);
    //     const dates = Object.keys(rawData[modules[0]] || {});
    
    //     const specialModules = ['Booked','Loaded', 'OBL Received', 'Draft Received', 'Received And Shared'];
    
    //     const dynamicColumns = [
    //         {
    //             title: 'Module',
    //             dataIndex: 'module',
    //             width: "250px",
    //             key: 'module',
    //             fixed: 'left',
    //             sorter: (a, b) => a.module.localeCompare(b.module),
    //             ...getColumnSearchProps('module'),
    //         },
    //         ...dates.map(date => ({
    //             title: date,
    //             dataIndex: date,
    //             key: date,
    //             align: 'center',
    //             sorter: (a, b) => (a[date] || 0) - (b[date] || 0),
    //             render: (value, record) => {
    //                 const isSpecialModule = specialModules.includes(record.module);
    //                 if (value === 0 && isSpecialModule) {
    //                     return <span style={{ color: 'orange', fontWeight: 'bold' }}>0 / NA</span>;
    //                 }
    //                 return (
    //                     <span style={{ color: value > 5 ? 'green' : 'black' }}>
    //                         {value}
    //                     </span>
    //                 );
    //             },
    //         })),
    //         {
    //             title: 'Total',
    //             dataIndex: 'total',
    //             key: 'total',
    //             align: 'center',
    //             sorter: (a, b) => a.total - b.total,
    //             fixed: 'right',
    //             render: (value, record) => {
    //                 const isSpecialModule = specialModules.includes(record.module);
    //                 if (value === 0 && isSpecialModule) {
    //                     return <span style={{ color: 'orange', fontWeight: 'bold' }}>0 / NA</span>;
    //                 }
    //                 return (
    //                     <span style={{ color: value > 5 ? 'green' : 'black' }}>
    //                         {value}
    //                     </span>
    //                 );
    //             },
    //         }
    //     ];
    
    //     const data = modules.map(module => {
    //         let row = { module };
    //         let total = 0;
    //         dates.forEach(date => {
    //             row[date] = rawData[module][date] || 0;
    //             total += row[date];
    //         });
    //         row['total'] = total;
    //         return row;
    //     });
    
    //     return { data, columns: dynamicColumns };
    // };


    const transformData = (rawData) => {
        const modules = Object.keys(rawData);
        const dates = Object.keys(rawData[modules[0]] || {});
    
        const specialModules = ['Enquiries','Costsheet','Purchase Order','GRN','Vehicle Assigned','Stock','Sale Order','Booked','Loaded', 'OBL Received', 'Draft Received', 'Received And Shared','Shipped','Invoice','Non-soaked Product Reportings','Expenses','Purchases'];
    
        const dynamicColumns = [
            {
                title: 'Module',
                dataIndex: 'module',
                width: "250px",
                key: 'module',
                fixed: 'left',
                sorter: (a, b) => a.module.localeCompare(b.module),
                ...getColumnSearchProps('module'),
            },
            ...dates.map(date => ({
                title: date,
                dataIndex: date,
                key: date,
                align: 'center',
                sorter: (a, b) => (a[date] || 0) - (b[date] || 0),
                render: (value, record) => {
                    const isSpecialModule = specialModules.includes(record.module);
    
                    if (value === 0) {
                        if (isSpecialModule) {
                            return <span style={{ color: 'orange', fontWeight: 'bold' }}>0 / NA</span>;
                        } else {
                            return <span style={{ color: 'red' }}>{value}</span>;
                        }
                    }
    
                    return (
                        <span style={{ color: value > 5 ? 'green' : 'black' }}>
                            {value}
                        </span>
                    );
                },
            })),
            {
                title: 'Total',
                dataIndex: 'total',
                key: 'total',
                align: 'center',
                sorter: (a, b) => a.total - b.total,
                fixed: 'right',
                render: (value, record) => {
                    const isSpecialModule = specialModules.includes(record.module);
    
                    if (value === 0) {
                        if (isSpecialModule) {
                            return <span style={{ color: 'orange', fontWeight: 'bold' }}>0 / NA</span>;
                        } else {
                            return <span style={{ color: 'red' }}>{value}</span>;
                        }
                    }
    
                    return (
                        <span style={{ color: value > 5 ? 'green' : 'black' }}>
                            {value}
                        </span>
                    );
                },
            }
        ];
    
        const data = modules.map(module => {
            let row = { module };
            let total = 0;
            dates.forEach(date => {
                row[date] = rawData[module][date] || 0;
                total += row[date];
            });
            row['total'] = total;
            return row;
        });
    
        return { data, columns: dynamicColumns };
    };
    
    
    
    // const exportExcel = async () => {
    //     const workbook = new ExcelJS.Workbook();
    //     const worksheet = workbook.addWorksheet("Usage Report");
    
    //     // Define columns
    //     worksheet.columns = columns.map(col => ({
    //         header: col.title,
    //         key: col.dataIndex,
    //         width: 15,
    //     }));
    
    //     // Apply background color to headers
    //     const headerRow = worksheet.getRow(1);
    //     headerRow.eachCell((cell) => {
    //         cell.fill = {
    //             type: "pattern",
    //             pattern: "solid",
    //             fgColor: { argb: "008000" }, // Green background
    //         };
    //         cell.font = { bold: true, color: { argb: "FFFFFF" } }; // White text
    //         cell.alignment = { horizontal: "center" };
    //     });
    
    //     // Add formatted data
    //     usageData.forEach(row => {
    //         const formattedRow: Record<string, any> = {};
    
    //         columns.forEach(col => {
    //             formattedRow[col.dataIndex] = row[col.dataIndex] || 0;
    //         });
    
    //         // Add row to the worksheet
    //         const newRow = worksheet.addRow(formattedRow);
    
    //         // Apply styling to numeric cells
    //         columns.forEach((col, index) => {
    //             const cell = newRow.getCell(index + 1);
    //             const value = cell.value;
    
    //             if (typeof value === "number") {
    //                 cell.font = {
    //                     color: { argb: value === 0 ? "FF0000" : value > 5 ? "008000" : "000000" },
    //                 };
    //             }
    //         });
    //     });
    
    //     // Generate and save file
    //     const buffer = await workbook.xlsx.writeBuffer();
    //     const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    //     saveAs(blob, "UsageReport.xlsx");
    // };

    const exportExcel = async () => {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet("Usage Report");
    
        const specialModules = ['Enquiries','Costsheet','Purchase Order','GRN','Vehicle Assigned','Stock','Sale Order','Booked','Loaded', 'OBL Received', 'Draft Received', 'Received And Shared','Shipped','Invoice','Non-soaked Product Reportings','Expenses','Purchases'];

    
        // Define columns
        worksheet.columns = columns.map(col => ({
            header: col.title,
            key: col.dataIndex,
            width: 15,
        }));
    
        // Apply background color to headers
        const headerRow = worksheet.getRow(1);
        headerRow.eachCell((cell) => {
            cell.fill = {
                type: "pattern",
                pattern: "solid",
                fgColor: { argb: "008000" }, // Green background
            };
            cell.font = { bold: true, color: { argb: "FFFFFF" } }; // White text
            cell.alignment = { horizontal: "center" };
        });
    
        // Add formatted data
        usageData.forEach(row => {
            const formattedRow = {};
    
            columns.forEach(col => {
                formattedRow[col.dataIndex] = row[col.dataIndex] || 0;
            });
    
            // Add row to the worksheet
            const newRow = worksheet.addRow(formattedRow);
            const isSpecialModule = specialModules.includes(row.module);
    
            // Apply styling to numeric cells
            columns.forEach((col, index) => {
                const cell = newRow.getCell(index + 1);
                let value = cell.value;
    
                if (col.dataIndex !== "module") { // Exclude module name from styling
                    if (typeof value === "number") {
                        if (value === 0) {
                            if (isSpecialModule) {
                                cell.value = "0 / NA"; // Set value as "0 / NA"
                                cell.font = { color: { argb: "FFA500" } }; // Orange color
                            } else {
                                cell.font = { color: { argb: "FF0000" } }; // Red for normal modules
                            }
                        } else if (value > 5) {
                            cell.font = { color: { argb: "008000" } }; // Green if greater than 5
                        } else {
                            cell.font = { color: { argb: "000000" } }; // Black for other numbers
                        }
                    }
                }
            });
        });
    
        // Generate and save file
        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        const today = new Date();
        const formattedDate = `(${String(today.getDate()).padStart(2, '0')}-${String(today.getMonth() + 1).padStart(2, '0')}-${today.getFullYear()})`;
        saveAs(blob, `Usage Report ${formattedDate}.xlsx`);
    };
    

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

    return (
        <Card
            title={<span style={{ color: 'white' }}>Usage Report</span>}
            style={{ textAlign: 'center' }}
            headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            size="small"
            extra={usageData.length > 0 && (
                <Button icon={<DownloadOutlined />} onClick={exportExcel}>
                    GET EXCEL
                </Button>
            )}
        >
            <Form form={form} layout="vertical" onFinish={getUsageData}>
                <Row gutter={24}>
                    <Col xs={24} sm={12} md={8} lg={6}>
                        <Form.Item name="dateRange" label="Date">
                            <RangePicker
                                allowClear
                                disabledDate={current => current && current > moment().endOf('day')}
                                defaultValue={[moment(), moment()]}
                                format="YYYY-MM-DD"
                            />
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item style={{ marginTop: "27px" }}>
                            <Button htmlType="submit" icon={<SearchOutlined />} type="primary">
                                Search
                            </Button>
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item style={{ marginTop: "27px", marginRight: '100px' }}>
                            <Button htmlType="reset" onClick={onReset} danger icon={<UndoOutlined />}>
                                Reset
                            </Button>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Table
                columns={columns}
                dataSource={usageData}
                rowKey="module"
                pagination={false}
                bordered
                scroll={{ x: 'max-content' }}
            />
        </Card>
    );
}

export default WhatsAppUsageReport;




