import React, { useRef, useState, useEffect } from "react";
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
import Button from '@mui/material/Button';
import axios from "axios";
import { getCookie, setCookie } from 'react-use-cookie';
import { useHistory } from "react-router-dom";
import { DataGrid, GridToolbar, frFR } from '@mui/x-data-grid';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { Editor } from '@tinymce/tinymce-react';
import { FcViewDetails, FcDisapprove } from "react-icons/fc";
import 'react-tooltip/dist/react-tooltip.css'
import { Tooltip } from 'react-tooltip'
import Checkbox from '@mui/material/Checkbox';
import excel_icone from "../mysy_img/excel_icone.png";

import fileDownload from 'js-file-download'
import { FcInfo } from "react-icons/fc";
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';

import { FcAcceptDatabase, } from "react-icons/fc";
import { format } from 'date-fns'
import InputAdornment from '@mui/material/InputAdornment';
import { AiFillCloseCircle, AiOutlineConsoleSql } from "react-icons/ai";
import Box from '@mui/material/Box';

import { CiTrash } from "react-icons/ci";
import { MdAddCircleOutline, MdRemoveCircleOutline } from "react-icons/md";
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import img_loading_spin from "./../mysy_img/mysy_spin_loading.gif";
import { Fab } from "@material-ui/core";
import { IoMdAddCircle, IoIosRemoveCircleOutline } from "react-icons/io";
import { AiTwotoneSave } from "react-icons/ai";
import { FcEditImage } from "react-icons/fc";
import ToggleSwitch from "./ToggleSwitch";

import { FcSpeaker } from "react-icons/fc";
import Autocomplete from '@mui/material/Autocomplete';
import { FcOpenedFolder } from "react-icons/fc";
import Module_Absence from "./Module_Absence";
import { RiMoreFill } from "react-icons/ri";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import moment from "moment";
import 'moment/locale/fr';
import { IoAddCircleOutline, IoCloseCircleOutline } from "react-icons/io5";
import { gridClasses } from '@mui/x-data-grid';
import Link from '@mui/material/Link';
import { PiDotsThree } from "react-icons/pi";
import {
    GridToolbarContainer, GridToolbarExport, GridToolbarColumnsButton,
    GridToolbarFilterButton, GridToolbarDensitySelector, GridToolbarExportContainer, useGridApiContext,
    gridFilteredSortedRowIdsSelector,
    gridVisibleColumnFieldsSelector,
    GridValueGetterParams,
    GridPreferencePanelsValue,

} from '@mui/x-data-grid';
import * as XLSX from 'xlsx';
import Module_Alert_Confirmation from "./Module_Alert_Confirmation";

import CancelPresentationIcon from '@mui/icons-material/CancelPresentation';
import { makeStyles } from "@material-ui/core/styles";
import Paper from '@material-ui/core/Paper';
import Draggable from 'react-draggable';
import { IconButton } from '@material-ui/core';

function PaperComponent(props) {
    return (
        <Draggable
            handle="#draggable-dialog-title"
            cancel={'[class*="MuiDialogContent-root"]'}
        >
            <Paper {...props} />
        </Draggable>
    );
}

const useStyles = makeStyles((theme) => ({

    dialog: {
        position: 'absolute',
        // left: 10,
        top: 400
    },

    paper: {
        overflowY: 'unset',
    },
    customizedButton: {
        position: 'absolute',
        left: '98%',
        top: '-3%',
        backgroundColor: 'lightgray',
        color: 'gray',
    },
}));

const Module_Ent_Mes_Documents = (props) => {

    const classes = useStyles();

    const history = useHistory();
    const [submenu, setsubmenu] = useState("");



    const filters = [
        { value: 'email', label: 'Email' },
        { value: 'nom', label: 'Nom' },
        { value: 'prenom', label: 'Prénom' }
    ]

    const [selectedfilt1, setselectedfilt1] = useState("");
    const [selectedfilt2, setselectedfilt2] = useState("");
    const [selectedfilt3, setselectedfilt3] = useState("");


    function ExpandableCell_50({ value }) {
        const [expanded, setExpanded] = React.useState(false);

        return (
            <nav>
                {value && <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>

                    {expanded ? value : value.slice(0, 50)}&nbsp;
                    {value.length > 50 && (
                        // eslint-disable-next-line jsx-a11y/anchor-is-valid
                        <Link
                            type="button"
                            component="button"
                            sx={{ fontSize: 'inherit' }}
                            onClick={() => setExpanded(!expanded)}
                        >
                            {expanded ? <nav>  <PiDotsThree />Réduire</nav> : <nav> <PiDotsThree />Voir</nav>}
                        </Link>
                    )}
                </div>}

                {value && <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>
                    &nbsp;
                </div>
                }
            </nav>
        );
    }



    function Display_Colunm_text({ value }) {

        return (
            <div style={{ paddingLeft: "5px", paddingRight: "10px", "display": "block", wordBreak: "break-all" }}>
                {value}&nbsp;

            </div>
        );
    }
    const columns_apprenant_inscriptions = [
        { field: 'id', headerName: 'id', hide: true },
        { field: '_id', headerName: '_id', hide: true },
        { field: 'session_id', headerName: 'session_id', hide: true, Width: 1 },
        { field: 'session_code', headerName: 'Code Session', hide: false, minWidth: 200, flex: 1, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'class_title', headerName: 'Titre Formation', hide: false, minWidth: 200, flex: 1, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'class_internal_url', headerName: 'class_internal_url', hide: true, Width: 1 },
        {
            field: 'status', headerName: 'Statut', hide: false, flex: 1, minWidth: 50, maxWidth: 70,
            valueFormatter: (params) => {
                if (String(params.value) === "0")
                    return "Pré.";
                else if (String(params.value) === "1")
                    return "Ins";
                else if (String(params.value) === "-1")
                    return "Ann";
                else if (String(params.value) === "2")
                    return "Enc";
                else
                    return "???";
            }
        },

        { field: 'client_rattachement_id', headerName: 'client__id', hide: true, Width: 1 },
        { field: 'client_rattachement_nom', headerName: 'Client', hide: false, minWidth: 200, flex: 1, renderCell: (params) => <ExpandableCell_50 {...params} />, },

        { field: 'date_debut', headerName: 'Début', hide: false, minWidth: 200, flex: 1, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'date_fin', headerName: 'Fin', hide: false, minWidth: 200, flex: 1, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'presentiel', headerName: 'Présentiel', hide: false, flex: 1, minWidth: 50, maxWidth: 70 },
        { field: 'distanciel', headerName: 'Distantiel', hide: false, flex: 1, minWidth: 50, maxWidth: 70 },

        { field: 'class_recyclage_delai', headerName: 'Recycl. Delai', hide: false, flex: 1, minWidth: 100, },
        { field: 'class_recyclage_periodicite', headerName: 'Recycl. Perio', hide: false, flex: 1, minWidth: 100, },
        { field: 'nb_jour_avant_recyclage', headerName: 'Jrs avant Recycl.', hide: false, flex: 1, minWidth: 100, },


        {
            field: "Detail", headerName: 'Voir détail',
            renderCell: (cellValues) => {
                return (

                    <Button

                        onClick={(event) => {

                            if (cellValues.row._id && String(cellValues.row._id).length > 2) {
                                var tmp = cellValues.row.session_code + "&" + cellValues.row.session_id + "&" + cellValues.row.class_internal_url + "&" + p_detail_email;

                                window.open(
                                    process.env.REACT_APP_FRONT_URL + "Partner/mes_stagiaires/" + String(cellValues.row._id) + "/" + String(tmp),
                                    '_blank'
                                );
                            }
                            //handleClick_edit_apprenant_From_Line(cellValues.row.id);
                        }}
                    >
                        <FcViewDetails />

                    </Button>

                );
            }
        },

        {
            field: "delete", headerName: 'Supprimer',
            renderCell: (cellValues) => {
                return (

                    <Popup
                        trigger={<Button

                        >
                            <CiTrash />

                        </Button>}
                        modal
                        nested
                        position="center center"
                    >
                        {close => (
                            <div>
                                <button className="gest_close" onClick={close}>
                                    &times;
                                </button>
                                <div className="gest_header"> MySy Information </div>
                                <div className="gest_content">
                                    {' '}

                                    En confirmant cette opération, l'inscription sera <i><font color="red"> définitivement supprimée</font></i>. <br />

                                </div>
                                <div className="gest_actions">
                                    <div style={{ "width": "45%", "float": "left" }}>
                                        <button className="gest_bton_popup" onClick={(event) => {
                                            //handleClick_delete_Apprenant(event, cellValues);

                                            close();
                                        }}> Valider </button>

                                    </div>
                                    <div style={{ "width": "45%", "float": "right" }}>
                                        <button
                                            className="gest_bton_popup"
                                            onClick={() => {
                                                //console.log('modal closed ');
                                                close();
                                            }}
                                        >
                                            Annuler
                                        </button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </Popup>


                );
            }
        },


    ]

    return (
        <div className="module_ent_mes_documents">

            {isLoading && <div className="loader-container">
                <div className="mysy_spinner">  <img src={img_loading_spin} />  </div>
            </div>}


            {/***  Affichage des messages d'alerte*/}
            {display_alert_mysy && String(display_alert_mysy) === "1" &&
                <Module_Alert_Confirmation alert_message={alert_message}
                    alert_type={alert_type}
                    clear_alert_message={clear_alert_message}
                    clear_alert_type={clear_alert_type}
                    clear_display_alert_mysy={clear_display_alert_mysy}
                />
            }
            {/*** FIN Affichage des messages d'alerte*/}


            <h3 style={{ fontFamily: 'DM Sans' }}> Mes Documents </h3>
            <div>
                <div className="titre1">  Utilisez les filtres !</div>
                <div className="div_row" style={{ "marginBottom": "5px" }}>
                    <div className="div_row_gauche texte_area_filter" >
                        <TextField
                            name="filtre1"
                            label="Choisir un champ"
                            select
                            sx={{ m: 1, width: '100%' }}
                            value={p_filtre1}
                            onChange={(e) => {
                                setp_filtre1(e.target.value)
                            }}
                        >

                            <MenuItem value="email" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }}>Email &nbsp;&nbsp;</MenuItem>
                            <MenuItem value="nom" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Nom &nbsp;</MenuItem>
                            <MenuItem value="prenom" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Prénom &nbsp;</MenuItem>

                        </TextField>
                    </div>



                    <div className="div_row_droite texte_area_filter_value" >
                        {p_filtre1 &&
                            <TextField
                                sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}
                                required
                                name="filtre1_value"
                                id="filtre1_value"

                                InputLabelProps={{
                                    shrink: true,
                                }}
                                disabled={false}
                                className="disabled_style"
                                value={p_filtre1_value}
                                onChange={(e) => { setp_filtre1_value(e.target.value); }}
                                InputProps={{
                                    endAdornment: (
                                        <InputAdornment position="end">
                                            <AiFillCloseCircle
                                                style={{ 'cursor': "pointer", "color": "orangered" }}
                                                onClick={(e) => {
                                                    setp_filtre1_value("");
                                                }} />
                                        </InputAdornment>
                                    ),
                                }}

                            />

                        }
                    </div>
                    {p_filtre1 && <div className='filter_bton_add'>
                        <Tooltip className="tooltip_css" id="my-tooltip01" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip01" data-tooltip-html="Ajouter une nouvelle ligne de filtre">
                            &nbsp; <MdAddCircleOutline onClick={(e) => {
                                setp_filtre2("1");
                            }} />
                        </a>
                    </div>}
                    {p_filtre1 && <div className='filter_bton_add'>
                        <Tooltip className="tooltip_css" id="my-tooltip02" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip02" data-tooltip-html="Supprimer cette ligne de filtre">
                            &nbsp; <MdRemoveCircleOutline onClick={(e) => {
                                setp_filtre1();
                                setp_filtre1_value();
                            }}
                            />
                        </a>
                    </div>}


                </div>

                {p_filtre2 &&
                    <div className="div_row" style={{ "marginBottom": "5px" }}>
                        <div className="div_row_gauche texte_area_filter">
                            <TextField
                                name="filtre2"
                                label="Choisir un champ"
                                select
                                sx={{ m: 1, width: '100%' }}
                                options={filters}
                                value={p_filtre2}
                                onChange={(e) => {
                                    setp_filtre2(e.target.value)
                                }}
                            >

                                <MenuItem value="email" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }}>Email &nbsp;&nbsp;</MenuItem>
                                <MenuItem value="nom" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Nom &nbsp;</MenuItem>
                                <MenuItem value="prenom" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Prénom &nbsp;</MenuItem>

                            </TextField>
                        </div>
                        <div className="div_row_droite texte_area_filter" >
                            {String(p_filtre2).length > 3 &&
                                <TextField
                                    sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}
                                    required
                                    name="filtre2_value"
                                    id="filtre2_value"

                                    InputLabelProps={{
                                        shrink: true,
                                    }}
                                    disabled={false}
                                    className="disabled_style"
                                    value={p_filtre2_value}
                                    onChange={(e) => setp_filtre2_value(e.target.value)}
                                    InputProps={{
                                        endAdornment: (
                                            <InputAdornment position="end">
                                                <AiFillCloseCircle
                                                    style={{ 'cursor': "pointer", "color": "orangered" }}
                                                    onClick={(e) => {
                                                        setp_filtre2_value("");
                                                    }} />
                                            </InputAdornment>
                                        ),
                                    }}

                                />}
                        </div>


                        {String(p_filtre2).length > 3 && <div className='filter_bton_add'>
                            <Tooltip className="tooltip_css" id="my-tooltip04" style={{ "fontSize": "12px" }} />
                            <a data-tooltip-id="my-tooltip04" data-tooltip-html="Supprimer cette ligne de filtre">
                                &nbsp; <MdRemoveCircleOutline
                                    onClick={(e) => {
                                        setp_filtre2();
                                        setp_filtre2_value();
                                    }}
                                />
                            </a>
                        </div>}
                    </div>
                }


                {<div className="div_row" style={{ "border": "None", "color": "orange", "textAlign": "center" }}>

                    <div className="div_row_gauche" style={{ "textAlign": 'left', 'marginLeft': '15px' }}>
                        <Button variant="contained" className="bton_enreg" onClick={"Get_All_Apprenant"}>Rechercher
                        </Button>
                    </div>

                    <div className="div_row_droite" style={{ "textAlign": 'right', 'marginRight': '15px' }}>
                        <Button variant="contained" className="bton_annule" onClick={"clean_all_filters"}>Annuler
                        </Button>

                    </div>

                </div>}

            </div>
            <br />

        </div >
    );
}

export default Module_Ent_Mes_Documents;