// material-ui
import * as React from 'react';
import {
    DataGrid,
    GridActionsCellItem,
} from "@mui/x-data-grid";
import EditIcon from '@mui/icons-material/Edit';
import {useEffect} from "react";
import {useNavigate} from "react-router-dom";
import {CustomNoRowsOverlay, dateComparator, getDateString} from "../../utils/CommonFunction";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";

// ==============================|| EVENT TABLE ||============================== //

export default function AppreciationTable({recordList, divisionRef}) {
    const [rows, setRows] = React.useState(recordList);
    const [rowModesModel] = React.useState({});

    const navigate = useNavigate()

    const [paginationModel, setPaginationModel] = React.useState({
        page: 0,
        pageSize:10
    });


    useEffect(() => {
        setPaginationModel({page:0,pageSize:10});
        setRows(recordList);
    }, [recordList]);

    const handleEditClick = (id) => () => {
        navigate('/appreciation/maintain/'+ id);
    };

    const columns = [
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 100,
            cellClassName: 'actions',
            getActions: ({id}) => {
                return [
                    <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem
                        key="OutSave"
                        icon={<EditIcon sx={{fontSize: 25}}/>}
                        label="Edit"
                        className="textPrimary"
                        onClick={handleEditClick(id)}
                        color="edit"
                    />
                    </ThemeProvider>
                ]
            },
        },
        {
            id: 'sbuIds',
            field: 'sbuIds',
            headerName: 'SUB / Division',
            flex: 0.75,
            renderCell: (params) => {
                const sbuIds = JSON.parse(params.value); // Parse the JSON string to an array
                const labels = sbuIds.map((item) => {
                    const division = divisionRef.find((div) => div.id === item.id); // Find the corresponding division object
                    return division ? division.label : ''; // Get the label or an empty string if not found
                });

                const renderedLabels = labels.filter(Boolean); // Remove empty strings from labels
                const displayedLabels = renderedLabels.join(', '); // Join the non-empty labels with a comma separator

                return (
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start', whiteSpace: 'normal', wordBreak: 'break-word' }}>
                        {displayedLabels}
                    </div>
                );
            }
        },
        {
            id: 'receiptDate',
            field: 'receiptDate',
            headerName: 'Receipt Date',
            flex: 0.6,
            //sortable: false,
            sortComparator: dateComparator,
            renderCell: (params) => {
                const dateString = getDateString(params.row.receiptDate,false).toString();
                return (
                    <div>
                        {dateString}
                    </div>
                );
            }
        },
        {
            id: 'description',
            field: 'description',
            //type: 'date',
            //sortable: false,
            headerName: 'Brief Description',
            flex: 2,
            renderCell: (params) => {
                const { value } = params;
                let truncatedValue = value;

                if (value.length > 300) {
                    truncatedValue = value.substring(0, 300) + '...';
                }

                return (
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', whiteSpace: 'normal'}}>
                        {truncatedValue}
                    </div>
                );
            }
        },
        {
            id: 'clientDepartment',
            field: 'clientDeptOrg',
            headerName: 'Client Department / Organization',
            flex: 1.5,
            renderCell: (params) => {
                return (
                    <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', whiteSpace: 'normal', wordBreak: 'break-word'}}>
                        {params.value}
                    </div>
                );
            }
        },
        {
            id: 'lnReceiptDate',
            field: 'lnReceiptDate',
            headerName: 'LN Receipt Date',
            //sortable: false,
            flex: 0.7,
            sortComparator: dateComparator,
            renderCell: (params) => {
                const dateString = getDateString(params.row.lnReceiptDate,false).toString();
                return (
                    <div>
                        {dateString}
                    </div>
                );
            }
        },
        {
            id: 'category',
            field: 'category',
            headerName: 'Category',
            flex: 0.5,
            renderCell: (params) => {
                return (
                    <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', whiteSpace: 'normal', wordBreak: 'break-word'}}>
                        {params.value}
                    </div>
                );
            }
        },
    ];

    return (
        <DataGrid
            disableColumnMenu
            rows={rows}
            columns={columns}
            columnHeaderHeight={45}
            editMode="row"
            rowModesModel={rowModesModel}
            getRowHeight={() => 'auto'}
            slots={{
                noRowsOverlay: () => (
                    CustomNoRowsOverlay()
                )
            }}
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
            pageSizeOptions={[10]}
            autoHeight
        />
    );
}
