// 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 axios from "axios";
import {apiPath} from "../../auth/utils";
import {
    GET_APPLICATION_EXTERNAL_REF_PATH,
    UPDATE_APPLICATION_EXTERNAL_REFERENCE_PATH,
} from "../../utils/ApiPathConst";
import {
    CustomNoRowsOverlay,
    GeneralConfirmWindow, notifyDeleteError, //getObjectById,
    notifyDeleteSuccess,
    notifySaveSuccess,
    removeObjectWithId
} from "../../utils/CommonFunction";
//import AbilityContext from "../../components/AbilityProvider";

let count = -1;
function EditToolbar(props) {
    const {setRows, setRowModesModel, canEdit} = props;
    console.log(canEdit );
    //const ability = useContext(AbilityContext);
    const handleClick = (id) => {
        setRows((oldRows) => [
            {
                id,
                isNew:true
            },
            ...oldRows,
        ]);
        setRowModesModel((oldModel) => ({
            ...oldModel,
            [id]: {mode: GridRowModes.Edit, fieldToFocus: 'remarks'},
        }));
    };

    return (
        <GridToolbarContainer sx={{ml: 1}}>
            <Button color="primary" startIcon={<AddIcon/>}
                    onClick={()=> handleClick(count--)}
                    disabled={canEdit}
            >
                Add External Link(s)
            </Button>
        </GridToolbarContainer>
    );
}

// ==============================|| EXTERNAL REFERENCE TABLE ||============================== //

export default function ExternalRefGrid({applicationId, canEdit}) {
    const [rows, setRows] = React.useState([]);
    const [rowModesModel, setRowModesModel] = React.useState({});
    //const ability = useContext(AbilityContext);
    //const [canUserEdit] = React.useState(!ability.can('EDIT','APPLICATION'));

// ==============================|| DELETE WINDOW RELATED ||============================== //
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);
    const [selectedId, setSelectedId] = React.useState(null);

    const handleClose = () => {
        setIsWindowOpen(false);
    };

    useEffect(() => {
        if(applicationId > 0 ){
            axios.get(`${apiPath}${GET_APPLICATION_EXTERNAL_REF_PATH}/${applicationId}`)
                .then((response) => {
                    if (response.status === 200) {
                        setRows(response.data.records);
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
    }, [applicationId]);

    const handleDeleteClick = (id) => () => {
        setIsWindowOpen(true);
        setSelectedId(id);
    };

    function updateData(){
        axios.delete(`${apiPath}${GET_APPLICATION_EXTERNAL_REF_PATH}/${selectedId}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    const newList =removeObjectWithId(rows,selectedId);
                    setIsWindowOpen(false);
                    setRows(newList);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

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

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

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

    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));
        }
    };

    function updateChannel(data) {
        axios.post(`${apiPath}${UPDATE_APPLICATION_EXTERNAL_REFERENCE_PATH}`,
            {
                "id": data.id,
                "remarks" : data.remarks,
                "refId" : applicationId
            },
        )
            .then((response) => {
                if (response.status === 200) {
                    const updatedRow = { ...data };
                    updatedRow.id = response.data.id;
                    if(data.id === -1){
                        setRows(rows.map((row) => (row.id === -1 ? updatedRow : row)));
                    }
                    else{
                        setRows(rows.map((row) => (row.id === data.id ? updatedRow : row)));
                    }
                    notifySaveSuccess();
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    const processRowUpdate = (newRow) => {
        return new Promise((resolve, reject) => {
            const updatedRow = { ...newRow, isNew: false };
            if (updatedRow.remarks.trim().length === 0) {
                const error = new Error('Name cannot be null');
                reject(error);
                return;
            }
            setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
            updateChannel(updatedRow);
            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 [
                        <GridActionsCellItem
                            key="InCancel"
                            icon={<CancelIcon sx={{fontSize: 25}}/>}
                            label="Cancel"
                            className="textPrimary"
                            disabled={canEdit}
                            onClick={handleCancelClick(id)}
                            color="error"
                        />,
                        <GridActionsCellItem
                            key="InSave"
                            icon={<SaveIcon sx={{fontSize: 25}}/>}
                            label="Save"
                            // sx={{
                            //     color: 'primary.main',
                            // }}
                            color="primary"
                            disabled={canEdit}
                            onClick={handleSaveClick(id)}
                        />,
                    ];
                }

                return [
                    <GridActionsCellItem
                        key="OutDelete"
                        icon={<DeleteIcon sx={{fontSize: 25}}/>}
                        label="Delete"
                        disabled={canEdit}
                        onClick={handleDeleteClick(id)}
                        color="error"
                    />,
                    <GridActionsCellItem
                        key="OutSave"
                        icon={<EditIcon sx={{fontSize: 25}}/>}
                        label="Edit"
                        className="textPrimary"
                        disabled={canEdit}
                        onClick={handleEditClick(id)}
                        color="warning"
                    />,
                ];
            },
        },
        {
            id: 'extRef',
            field: 'remarks',
            headerName: 'External Attachment Reference',
            flex: 1,
            editable: true,
            renderCell: (params) => (
                <a href={params.value} target="_blank" rel="noopener noreferrer" >
                    {params.value}
                </a>
            ),
        },
    ];

    return (
        <div style={{height: '100%', width: '100%'}}>

            <DataGrid
                rows={rows}
                columns={columns}
                columnHeaderHeight={45}
                editMode="row"
                rowModesModel={rowModesModel}
                onRowModesModelChange={handleRowModesModelChange}
                onRowEditStop={handleRowEditStop}
                processRowUpdate={processRowUpdate}
                onProcessRowUpdateError={(error) => {
                    console.log(error);
                    notifyDeleteError(`Link cannot be null`);
                }}
                initialState={{
                    pagination: {
                        paginationModel: {page: 0, pageSize: 10},
                    },
                }}
                slots={{
                    toolbar: EditToolbar,
                    noRowsOverlay: () => (
                        CustomNoRowsOverlay()
                    )
                }}
                pageSizeOptions={[5,10, 20]}
                slotProps={{
                    toolbar: {setRows, setRowModesModel, canEdit},
                }}
                autoHeight
            />
            <GeneralConfirmWindow
                isWindowOpen={isWindowOpen}
                title={"Attention"}
                //content={`Confirm to delete Reference ${getObjectById(rows,selectedId) === null ? "" : '"' + getObjectById(rows,selectedId).remarks + '"'} ?`}
                content={`Are you sure to delete this external link?`}
                onNormalClose={handleClose}
                onConfirmClose={updateData}
            />
        </div>
    );
}
