// material-ui
import * as React from 'react';
import {
    DataGrid,
    GridRowModes
} from "@mui/x-data-grid";
import { useEffect } from "react";
import { createDeleteFileColumn } from 'utils/fileListColumns';
// import {useNavigate} from "react-router-dom";
// import { useTheme } from '@mui/material/styles';
import {
    Box,
    Stack,
    Button
} from '@mui/material';
// ==============================|| EVENT TABLE ||============================== //

export default function UploadFileTable({ recordList, setRecordList, showPageColumn, _checkCode, _expectedCode }) {
    const [rows, setRows] = React.useState(recordList);
    const [rowModesModel, setRowModesModel] = React.useState({});
    const [showPage, setShowPage] = React.useState(false);
    const [checkCode, setCheckCode] = React.useState("");
    const [expectedCode, setExpectedCode] = React.useState("");
    // const theme = useTheme();

    // const navigate = useNavigate()

    useEffect(() => {
        setCheckCode(_checkCode)
    }, [_checkCode]);

    useEffect(() => {
        setExpectedCode(_expectedCode)
    }, [_expectedCode]);

    useEffect(() => {
        setRows(recordList);
        // console.log(disableDelete);
    }, [recordList]);

    useEffect(() => {
        setShowPage(showPageColumn);
        // console.log(disableDelete);
    }, [showPageColumn]);

    function NoRowsOverlay() {
        return (
            <Stack height="100%" alignItems="center" justifyContent="center">
                No File Record
                {/* <pre>(rows=&#123;[]&#125;)</pre> */}
            </Stack>
        );
    }

    const handleCancelClick = (id) => () => {
        setRowModesModel({
            ...rowModesModel,
            [id]: { mode: GridRowModes.View, ignoreModifications: true },
        });
        // console.log("Starting Delete")
        // const editedRow = rows.find((row) => row.id === id);
        // console.log(editedRow)
        // console.log(editedRow.isNew)
        setRecordList(rows.filter((row) => row.id !== id));
        setRows(rows.filter((row) => row.id !== id));
    }

    const deleteColumn = createDeleteFileColumn((id) => handleCancelClick(id));

    const handlePreviewClick = (param) => () => {
        var reader = new FileReader();
        reader.onload = function () {
            let path = reader.result;
            var pdf_newTab = window.open("");
            pdf_newTab.document.write(
                "<html>"
                + "<head><title>" + param.row.name + "</title></head>"
                + "<body>"
                + "<iframe title='" + param.row.name + "' width='100%' height='100%' src='" + path + "" + "'></iframe>"
                + "</body>"
                + "</html>"
            );
        };
        reader.readAsDataURL(param.row);
    }



    const columns = showPage?[
        deleteColumn,
        {
            field: 'name',
            headerName: 'File Name',
            flex: 1,
            renderCell: (params) => {
                return <Button onClick={handlePreviewClick(params)}><u>{params.row.name}</u></Button>;
            },
        },
        {
            id: 'size',
            field: 'size',
            headerName: 'File Size',
            valueGetter: (params) => {
                // console.log(params)
                return Math.ceil(params.value / 1024) + " KB";
            },
            flex: 1,
        },
        {
            id: 'no_of_page',
            field: 'no_of_page',
            headerName: 'Page',
            flex: 1,
            hide: true
        },
    ]:[
        deleteColumn,
        {
            field: 'name',
            headerName: 'File Name',
            flex: 1,
            renderCell: (params) => {
                return <Button onClick={handlePreviewClick(params)}><u>{params.row.name}</u></Button>;
            },
        },
        {
            id: 'check_code',
            field: 'check_code',
            headerName: 'File Code',
            flex: 1,
            hide: true,
            renderCell: () => {
                return (expectedCode == checkCode)?checkCode:<div style={{ margin: 4, color:"red" }}>Warning, File Code not match.<br/>File Code: {checkCode}<br/>Expected Code: {expectedCode}</div>;
            },
        },
        {
            id: 'size',
            field: 'size',
            headerName: 'File Size',
            valueGetter: (params) => {
                // console.log(params)
                return Math.ceil(params.value / 1024) + " KB";
            },
            flex: 1,
        },
    ];

    return (
        <Box style={{ height: '200px', width: '100%' }}>
            <DataGrid
                rows={rows}
                columns={columns}
                editMode="row"
                sx={{ border: 1 }}
                rowModesModel={rowModesModel}
                disablePagination
                components={{ NoRowsOverlay, }}
                // hideFooterPagination={true}
                disableSelectionOnClick
                disableColumnMenu
                disableColumnSelector
                hideFooter
                getRowHeight={() => 'auto'}
            />
        </Box>
    );
}
