// material-ui
import * as React from 'react';
import {
    DataGrid,
    GridActionsCellItem,
} from "@mui/x-data-grid";
import AssignmentTurnedInOutlinedIcon from '@mui/icons-material/AssignmentTurnedInOutlined';
import NotificationsOffRoundedIcon from '@mui/icons-material/NotificationsOffRounded';
import {
    CustomNoRowsOverlay, getObjectById, notifySaveSuccess,
} from "../../utils/CommonFunction";
import {Typography} from "@mui/material";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
import axios from "axios";
import {apiPath, getUserData} from "../../auth/utils";
import {POST_TODO_MARK_READ, POST_TODO_MARK_SUPPRESS} from "../../utils/ApiPathConst";
import {useContext} from "react";
import AbilityContext from "../../components/AbilityProvider";

export default function ReminderTable({recordList, isReaded, fetchList,value, isReminder}) {
    const [rows, setRows] = React.useState(recordList);
    const [rowModesModel] = React.useState({});
    const userData = getUserData();
    const ability = useContext(AbilityContext);


    const handleSuppressClick = (id) => () => {
        axios.post(`${apiPath}${POST_TODO_MARK_SUPPRESS}/${id}/${userData.id}`,{
        })
            .then((response) => {
                if (response.status === 200) {
                    fetchList(value);
                    notifySaveSuccess();
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    };

    const handleReadClick = (id) => () => {
        axios.post(`${apiPath}${POST_TODO_MARK_READ}/${id}/${userData.id}`,{
        })
            .then((response) => {
                if (response.status === 200) {
                    setRows(rows.filter((row) => row.id !== id));
                    notifySaveSuccess();
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    };

    // const getRowHeight = (params) => {
    //     const message = params.model.message; // Assuming the 'message' field is present in the data
    //     const lines = message.split("\\n").length;
    //
    //     const SINGLE_LINE_HEIGHT = 40;
    //     const HEIGHT_WITH_PADDING = 20;
    //     const LINE_HEIGHT = 24; // Adjust this value based on your font size and row padding
    //     const height = lines < 2 ? SINGLE_LINE_HEIGHT : HEIGHT_WITH_PADDING*2 + (LINE_HEIGHT * (lines-2) );
    //     console.log(height);
    //     return height <= SINGLE_LINE_HEIGHT ? SINGLE_LINE_HEIGHT : height;
    // };

    const columns = [
        {
            id: 'title',
            field: 'title',
            headerName: 'Title',
            //headerAlign: 'center',
            //align: 'center',
            flex:  2,
            renderCell: (params) => {
                return (
                    <div style={{ alignItems: 'flex-start', justifyContent: 'flex-start' }}>
                        <Typography
                            component="div"
                            variant="lionerDetailSize"
                            style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word', textAlign: 'left',  alignItems: 'flex-start' }}
                        >
                            {params.row.title}
                        </Typography>
                    </div>
                );
            }
        },
        {
            id: 'message',
            field: 'message',
            headerName: 'Message',
            flex:  3 ,
            renderCell: (params) => {
                const detail = params.row.message;
                const detailLines = detail.split("\\n").map((line, index) => {
                    const lineWithTabs = line.replaceAll("\\t", '\t'); // Replace \t with four non-breaking spaces
                    return (
                        <Typography
                            key={index}
                            component="div"
                            variant="lionerDetailSize"
                            style={{whiteSpace: 'pre-wrap', wordWrap: 'break-word'}}
                        >
                            {lineWithTabs}
                        </Typography>
                    )
                });

                return <div>{detailLines}</div>;
            },
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: !isReminder ? 'Read' : 'Read/ Suppress',
            width: 200,
            cellClassName: 'actions',
            getActions: ({id}) => {
                const row = getObjectById(rows,id);
                //console.log(row.suppressedBy)
                return !isReminder?
                    isReaded?
                        [
                            <ThemeProvider key="theme" theme={LIONER_BUTTON_THEME}>
                            </ThemeProvider>
                        ]
                        :
                        [
                            <ThemeProvider key="theme" theme={LIONER_BUTTON_THEME}>
                                <GridActionsCellItem

                                    key="markRead"
                                    icon={<AssignmentTurnedInOutlinedIcon sx={{fontSize: 25}}/>}
                                    label="Read"
                                    onClick={handleReadClick(id)}
                                    color="create"
                                />
                            </ThemeProvider>
                            ,
                        ]
                    :
                isReaded?
                    [
                        <ThemeProvider key="theme" theme={LIONER_BUTTON_THEME}>
                            <GridActionsCellItem
                                key="Suppress"
                                icon={<NotificationsOffRoundedIcon sx={{fontSize: 25}}/>}
                                label="Suppress"
                                className="textPrimary"
                                onClick={handleSuppressClick(id)}
                                color="delete"
                                disabled={row.suppressedBy === null ? !ability.can('SUPPRESS','REMINDER') : true}
                            />
                        </ThemeProvider>,
                    ]
                    :
                    [
                    <ThemeProvider key="theme" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem

                        key="markRead"
                        icon={<AssignmentTurnedInOutlinedIcon sx={{fontSize: 25}}/>}
                        label="Read"
                        onClick={handleReadClick(id)}
                        color="create"
                    />
                    </ThemeProvider>
                    ,
                    <ThemeProvider key="theme" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem
                        key="Suppress"
                        icon={<NotificationsOffRoundedIcon sx={{fontSize: 25}}/>}
                        label="Suppress"
                        className="textPrimary"
                        onClick={handleSuppressClick(id)}
                        disabled={!ability.can('SUPPRESS','REMINDER') }
                        color="delete"
                    />
                    </ThemeProvider>,
                ]
            },
        },
    ];

    return (
        <div style={{height: '33vh', width: '100%'}}>
            <DataGrid
                rows={rows}
                columns={columns}
                columnHeaderHeight={45}
                editMode="row"
                rowModesModel={rowModesModel}
                disableColumnMenu
                getRowHeight={() => 'auto'}
                //getRowHeight={getRowHeight}
                initialState={{
                    pagination: {
                        paginationModel: {page: 0, pageSize: 10},
                    },
                }}
                slots={{
                    noRowsOverlay: () => (
                        CustomNoRowsOverlay()
                    )
                }}
                pageSizeOptions={[10, 15, 20]}
                //autoHeight
            />
        </div>
    );
}
