// material-ui
import * as React from 'react';
import {
    DataGrid,
    GridActionsCellItem,
} from "@mui/x-data-grid";
import EditIcon from '@mui/icons-material/Edit';
import {useContext, useEffect} from "react";
import {useNavigate} from "react-router-dom";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import {
    CustomNoRowsOverlay,
    GeneralConfirmWindow,
    notifyDeleteSuccess,
    removeObjectWithId
} from "../../utils/CommonFunction";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_DIVISION_LIST} from "../../utils/ApiPathConst";
import UploadContext from "../../components/UploadProvider";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
//import {isObjEmpty} from "../../utils/Utils";

export default function DivisionTable({recordList}) {
    const [rows, setRows] = React.useState(recordList);
    const [rowModesModel] = React.useState({});
    const navigate = useNavigate();
    const { setIsUploading } = useContext(UploadContext);

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

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

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

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

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

    // const getRowHeight = (params) => {
    //     let temp = "";
    //     params.model.subDivision.map(function(input){
    //             temp = temp + input.name + ",";
    //         }
    //     );
    //     if(!isObjEmpty(temp)){
    //         const SINGLE_LINE_HEIGHT = 40;
    //         const HEIGHT_WITH_PADDING = 35;
    //         const LINE_HEIGHT = 25; // Adjust this value based on your font size and row padding
    //         const numberOfLines = Math.ceil(temp.length / 110); // Change 50 to your desired line length
    //         const height = numberOfLines < 2 ? SINGLE_LINE_HEIGHT : HEIGHT_WITH_PADDING*2 + (LINE_HEIGHT * (numberOfLines-2) );
    //         //console.log(height);
    //         return height <= SINGLE_LINE_HEIGHT ? SINGLE_LINE_HEIGHT : height;
    //     }
    //     else {
    //         return 40;
    //     }
    // };

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

    function getSubDivisionDisplay (subDivisionList){
        let tempString = "";
        for(let i = 0 ; i < subDivisionList.length ; i++){
            if (i !== subDivisionList.length-1){
                tempString = tempString + subDivisionList[i].name + ", "
            }
            else{
                tempString = tempString + subDivisionList[i].name
            }
        }
        //console.log(ele.name)
        return tempString
    }

    const columns = [
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 100,
            cellClassName: 'actions',
            getActions: ({id}) => {
                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: 'division',
            field: 'name',
            headerName: 'Division',
            flex: 0.8,
        },
        {
            id: 'subDivision',
            field: 'subDivision',
            headerName: 'Sub Division',
            flex: 1.2,
            // valueGetter: ({ row }) => {
            //     return <div>
            //
            //     </div>;
            // },
            renderCell: (params) => (
                <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center', whiteSpace: 'normal', wordBreak: 'break-word'}}>
                    {getSubDivisionDisplay(params.row.subDivision)}
                </div>

            ),
        },
    ];

    return (
        <div style={{/*maxHeight: '65vh',*/ width: '100%'}}>
            <DataGrid
                rows={rows}
                columns={columns}
                columnHeaderHeight={45}
                editMode="row"
                rowModesModel={rowModesModel}
                getRowHeight={() => 'auto'}
            paginationModel={paginationModel}
            onPaginationModelChange={setPaginationModel}
                slots={{
                    noRowsOverlay: () => (
                        CustomNoRowsOverlay()
                    )
                }}
                pageSizeOptions={[10]}
                autoHeight
            />
            <GeneralConfirmWindow
                isWindowOpen={isWindowOpen}
                title={"Attention"}
                //content={`Confirm to delete Division ${getObjectById(rows,selectedId) === null? "" : '"' + getObjectById(rows,selectedId).name + '"'} ?`}
                content={`Are you sure to delete this division?`}
                onNormalClose={handleClose}
                onConfirmClose={updateData}
            />
        </div>
    );
}
