// material-ui
import * as React from 'react';
import {
    Button,
} from '@mui/material';
import {
    DataGrid,
    GridActionsCellItem,
    GridRowEditStopReasons,
    GridRowModes,
    GridToolbarContainer
} from "@mui/x-data-grid";
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
//import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import AddIcon from '@mui/icons-material/Add';
import {useEffect} from "react";
import {CustomNoRowsOverlay, notifyDeleteError} from "../../utils/CommonFunction";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
import DoneIcon from '@mui/icons-material/Done';
import {GridPreProcessEditCellProps} from "@mui/x-data-grid";
//import {useEffect} from "react";

// ==============================|| EVENT TABLE - COLUMN  ||============================== //

let customerCount = -1;
function EditToolbar(props) {
    const {setRows, setRowModesModel} = props;

    const handleClick = (id) => {
        setRows((oldRows) => [
            {
                id,
                isNew:true
            },
            ...oldRows,
        ]);
        setRowModesModel((oldModel) => ({
            ...oldModel,
            [id]: {mode: GridRowModes.Edit, fieldToFocus: 'name'},
        }));
    };

    return (
        <GridToolbarContainer>
            <Button color="primary" startIcon={<AddIcon/>}
                    onClick={()=> handleClick(customerCount--)}
            >
                Add Sub-Division
            </Button>
        </GridToolbarContainer>
    );
}

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

export default function SubDivisionTable({divisionData, isCollectData,
                                             updateSubDivisionList}) {
    const [rows, setRows] = React.useState([]);
    const [rowModesModel, setRowModesModel] = React.useState({});
    const [deletedList, setDeletedList] = React.useState([]);

    useEffect(()=>{
        setRows(divisionData);
    },[divisionData]);

    useEffect(() => {
        //upload latest data to parent
        let allRecordSaved = true;
        Object.keys(rowModesModel).forEach((id) => {
            const rowMode = rowModesModel[id];
            if (rowMode.mode === GridRowModes.Edit) {
                allRecordSaved = false;
            }
        });
        updateSubDivisionList({
                "records": rows,
                "deletedList": deletedList
            },
            allRecordSaved);
    }, [isCollectData]);

    const handleRowEditStop = (params, event) => {
        if (params.reason === GridRowEditStopReasons.rowFocusOut) {
            event.defaultMuiPrevented = true;
        }
    };

    const handleEditClick = (id) => () => {
        setRowModesModel({...rowModesModel, [id]: {mode: GridRowModes.Edit, fieldToFocus: 'name'}});
    };

    const handleSaveClick = (id) => () => {
        setRowModesModel({...rowModesModel, [id]: {mode: GridRowModes.View, fieldToFocus: 'name'}});
    };

    const handleDeleteClick = (id) => () => {
        if(id >0){
            const temp = [...deletedList, id];
            setDeletedList(temp);
        }
        setRows(rows.filter((row) => row.id !== id));
    };

    const handleCancelClick = (id) => () => {
        setRowModesModel({
            ...rowModesModel,
            [id]: {mode: GridRowModes.View, ignoreModifications: true},
        });
        const editedRow = rows.find((row) => row.id === id);
        if (editedRow.isNew) {
            setRows(rows.filter((row) => row.id !== id));
        }
    };

    const processRowUpdate = (newRow) => {
        return new Promise((resolve, reject) => {
            const updatedRow = { ...newRow, isNew: false };
            if (updatedRow.name.trim().length === 0) {
                const error = new Error('Name cannot be null');
                reject(error);
                return;
            }
            setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
            resolve(updatedRow); // Resolve the Promise with the updated row
        });
    };

    const handleRowModesModelChange = (newRowModesModel) => {
        setRowModesModel(newRowModesModel);
    };

    const columns = [
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 100,
            cellClassName: 'actions',
            getActions: ({id}) => {
                const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

                if (isInEditMode) {
                    return [
                        <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                        <GridActionsCellItem
                            key="InCancel"
                            icon={<CancelIcon sx={{fontSize: 25}}/>}
                            label="Cancel"
                            className="textPrimary"
                            onClick={handleCancelClick(id)}
                            color="delete"
                        />
                        </ThemeProvider>,
                        <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                        <GridActionsCellItem
                            key="InSave"
                            icon={<DoneIcon sx={{fontSize: 25}}/>}
                            label="Save"
                            color='create'
                            onClick={handleSaveClick(id)}
                        />
                        </ThemeProvider>,

                    ];
                }

                return [
                    <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem
                        key="OutDelete"
                        icon={<DeleteIcon sx={{fontSize: 25}}/>}
                        label="Delete"
                        onClick={handleDeleteClick(id)}
                        color="delete"
                    />
                    </ThemeProvider>,
                    <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: 'subDivision',
            field: 'name',
            headerName: 'Sub-Division',
            flex: 1,
            editable: true,
            preProcessEditCellProps: (params: GridPreProcessEditCellProps) => {
                const hasError = params.props.value.length > 255;
                if(hasError){
                    notifyDeleteError("Input have reach the length limit(255)")
                }
                return { ...params.props, error: hasError };
            },
        },
    ];

    return (
        <DataGrid
            rows={rows}
            columns={columns}
            columnHeaderHeight={45}
            editMode="row"
            rowModesModel={rowModesModel}
            onRowModesModelChange={handleRowModesModelChange}
            onRowEditStop={handleRowEditStop}
            processRowUpdate={processRowUpdate}
            onProcessRowUpdateError={(error) => {
                console.log(error);
                notifyDeleteError(`Name cannot be null`);
            }}
            initialState={{
                pagination: {
                    paginationModel: {page: 0, pageSize: 10},
                },
            }}
            slots={{
                toolbar: EditToolbar,
                noRowsOverlay: () => (
                    CustomNoRowsOverlay()
                )
            }}
            getRowHeight={() => 'auto'}
            pageSizeOptions={[10]}
            slotProps={{
                toolbar: {setRows, setRowModesModel},
            }}
            autoHeight
        />
    );
}
