// material-ui
import React, {useContext, useEffect, useState} from 'react';
import MainCard from "../../components/MainCard";
import Image from "mui-image";
import {Box, CardContent, Grid, Typography} from "@mui/material";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {DELETE_FILE_PATH, GET_FILE_PATH} from "../../utils/ApiPathConst";
import IconButton from '@mui/material/IconButton';
import ClearIcon from '@mui/icons-material/Clear';
import {GENERAL_INFO_COLOR, GENERAL_RED_COLOR, GENERAL_SETTING_COLOR} from "../../themes/colorConst";
import {
    GeneralConfirmWindow,
    notifyDeleteSuccess,
    //removeObjectWithId,
    UploadFileWindow
} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
//import AbilityContext from "../../components/AbilityProvider";
import {LIONER_FORM_THEME} from "../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";
import 'assets/style/imageOverlay.css';
import DownloadIcon from '@mui/icons-material/Download';
import SettingsRoundedIcon from '@mui/icons-material/SettingsRounded';
import doc from 'assets/images/display/doc.png';
// material-ui

const FilePreviewGrid = ({fileList, reloadList, canEdit}) => {

    const [imageList, setImageList] = useState([]);
    const { setIsUploading } = useContext(UploadContext);
    //const ability = useContext(AbilityContext);

    useEffect(() => {
       setImageList(fileList);
    }, [fileList]);

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

    const [isUploadWindowOpen, setIsUploadWindowOpen] = React.useState(false);
    const [selectedVideo, setSelectedVideo] = React.useState({});

    const handleUploadWindowClose = () => {
        setIsUploadWindowOpen(false);
    };

    const handleUploadWindowSuccess = () =>{
        setIsUploadWindowOpen(false);
        reloadList();
    }

    const handleUploadThumbnail = (video) => () =>{
        setIsUploadWindowOpen(true);
        setSelectedVideo(video);
    }

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

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

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


    const downloadFile = (fileId, skey, filename) => () => {
        setIsUploading(true);
        axios.get(`${apiPath}${GET_FILE_PATH}/${fileId}/${skey}/${filename}`,{ responseType: 'blob' })
            .then((response) => {
                if (response.status === 200) {
                    const url = URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement("a");
                    link.href = url;
                    link.setAttribute("download", filename);
                    link.click();
                    setIsUploading(false);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    };

    return (
        <MainCard xs={12} md={12} lg={12}
                  border={false}
                  content={false}>
            <Grid item xs={12} md={12} lg={11.9}>
                <ThemeProvider theme={LIONER_FORM_THEME}>
                    <Grid container columnSpacing={1}>
                    {imageList.map((thumbnail ) => {
                        // Return the element. Also pass key
                        return (
                            <Grid item key={thumbnail.key}  sx={{ mb:1.5}} xs={6} s={6} md={6} lg={3} >
                                <MainCard sx={{ ml:1, mt:0.5, mb:0.5, mr:1, height: "100%", width:"100%"}}>
                                    {
                                        !canEdit?
                                            <Grid container justifyContent="space-between" alignItems="center">
                                                <Grid item>
                                                    <IconButton aria-label="delete" size="medium" onClick={handleDeleteClick(thumbnail.fileId)}>
                                                        <ClearIcon fontSize="medium" sx={{color:GENERAL_RED_COLOR}}/>
                                                    </IconButton>
                                                </Grid>
                                                <Grid item>
                                                    <IconButton aria-label="delete" size="medium" onClick={handleUploadThumbnail(thumbnail)}>
                                                        <SettingsRoundedIcon fontSize="medium" sx={{color:GENERAL_SETTING_COLOR}}/>
                                                    </IconButton>
                                                </Grid>
                                            </Grid>
                                            :
                                            undefined
                                    }
                                    <CardContent sx={{display: "grid", placeItems: "center"}}>
                                        <Box sx={{ ml: 1, mr: 1, mt: 1, height: '100%', width: thumbnail.fileSize === 0 ? '70px' : '75%' }}>
                                            <div className="container"  >
                                                <Image
                                                    className="image"
                                                    src={thumbnail.fileSize === 0 ? doc : thumbnail.src}
                                                />
                                                <Box
                                                    className="overlay"
                                                    onClick={downloadFile(thumbnail.fileId, thumbnail.skey, thumbnail.filename)}
                                                >
                                                    <div className="text">
                                                        <DownloadIcon sx={{ fontSize: thumbnail.fileSize === 0 ? 50 : 100 }} />
                                                    </div>
                                                </Box>
                                            </div>
                                        </Box>
                                        <Box sx={{ml: 3, mr: 3, maxWidth:'100%', display: 'flex', alignItems: 'center', flexDirection: 'column', justifyContent: 'space-between'}}>
                                        <Grid container>
                                                <Grid item xs={12} s={12} md={12} lg={12}>
                                                    <Typography align="center" variant="body1" wrap="true" sx={{mt:2,ml:3,mr:3}}
                                                                onClick={downloadFile(thumbnail.fileId, thumbnail.skey, thumbnail.filename)}
                                                    >
                                                        <Typography
                                                            variant="lionerLabel"
                                                            component="span"
                                                            sx={{
                                                                wordBreak: 'break-all',
                                                                overflowWrap: 'break-word',
                                                            }}
                                                        >
                                                            {thumbnail.filename}
                                                        </Typography>
                                                    </Typography>
                                                </Grid>
                                            </Grid>
                                        </Box>
                                        {
                                            thumbnail.remarks === "" || thumbnail.remarks === null ?
                                                <Grid/>
                                                :
                                                <Grid container>
                                                    <Grid item xs={12} s={12} md={12} lg={12} sx={{ mt:2,mb:1 , display: 'flex', alignItems: 'center'}}>
                                                        <Typography variant="lionerSubLabel" color={GENERAL_INFO_COLOR} component="span">
                                                            Description:
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12} s={12} md={12} lg={12} sx={{ mt:1,ml:1,mr:1, mb:1}}justifyContent="space-between" alignItems="right">
                                                        <Typography variant="lionerLabel" component="span">
                                                            {thumbnail.remarks.split("\n").map((line, index) => {
                                                                return (
                                                                    <Typography
                                                                        key={index}
                                                                        sx={{
                                                                            wordBreak: 'break-all',
                                                                            overflowWrap: 'break-word',
                                                                        }}
                                                                    >
                                                                        {line}
                                                                    </Typography>
                                                                )
                                                            })}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                        }

                                    </CardContent>
                                </MainCard>
                            </Grid>)
                    })}
                </Grid>
                <UploadFileWindow
                    isWindowOpen={isUploadWindowOpen}
                    title={"File Configuration"}
                    video={selectedVideo}
                    onNormalClose={handleUploadWindowClose}
                    onConfirmClose={handleUploadWindowSuccess}
                />
                <GeneralConfirmWindow
                    isWindowOpen={isWindowOpen}
                    title={"Attention"}
                    content={`Are you sure to delete this attachment? \nNotes: This action is not able to be undone or retrieved.`}
                    onNormalClose={handleClose}
                    onConfirmClose={updateData}
                />
                </ThemeProvider>
            </Grid>
        </MainCard>
    );
};

export default FilePreviewGrid;
