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 CheckOut from "./CheckOut";
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 parse from 'html-react-parser';
import { FcViewDetails, FcDisapprove } from "react-icons/fc";
import 'react-tooltip/dist/react-tooltip.css'
import { Tooltip } from 'react-tooltip'
import add_plus from "../mysy_img/plus.png";
import excel_icone from "../mysy_img/excel_icone.png";
import participants from "../mysy_img/participants.png";
import fileDownload from 'js-file-download'
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import { FcCancel, FcApproval, FcAcceptDatabase, FcPrint } from "react-icons/fc";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { format } from 'date-fns'
import moment from "moment";
import InputAdornment from '@mui/material/InputAdornment';
import { AiFillCloseCircle } from "react-icons/ai";
import Box from '@mui/material/Box';
import { Typography, LinearProgress, sliderClasses } from '@mui/material';
import styled from 'styled-components';
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 { TransitionProps } from '@mui/material/transitions';
import img_loading_spin from "./../mysy_img/mysy_spin_loading.gif";


const Module_Absence = (props) => {


    const myconntected_employee_id = props.conntected_employee_id;
    const [selected_employee_id, setselected_employee_id] = useState(props.conntected_employee_id);

    const history = useHistory();
    const [rowss, setRows] = useState([]);
    const [selectionModel, setSelectionModel] = React.useState([]);

    var date_today_90j = new Date();
    date_today_90j.setDate(date_today_90j.getDate() + 90);

    const [p_filtre1, setp_filtre1] = useState();
    const [p_filtre1_value, setp_filtre1_value] = useState();

    const [p_filtre2, setp_filtre2] = useState();
    const [p_filtre2_value, setp_filtre2_value] = useState();

    const [isLoading, setLoading] = useState();

    const columns = [
        { field: '_id', headerName: '_id', hide: true },
        { field: 'id', headerName: 'id', hide: true },
        { field: 'event_start', headerName: 'Du', flex: 1, hide: false, editable: false },
        { field: 'event_end', headerName: 'Au', flex: 1, hide: false, editable: false },
        { field: 'justified', headerName: 'Justifier', flex: 1, hide: true, editable: false },
        { field: 'event_title', headerName: 'Title', flex: 1, hide: true, editable: false },

        
         {/*
             field: "delete", headerName: 'Supprimer',
             renderCell: (cellValues) => {
                 return (
 
                     <Popup
                         trigger={<Button
 
                             onClick={(event) => {
                                 // handleClick_delete(event, cellValues);
                             }}
                         >
                             <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, le document sera <i><font color="red"> définitivement supprimé</font></i>. <br />
 
                                 </div>
                                 <div className="gest_actions">
                                     <div style={{ "width": "45%", "float": "left" }}>
                                         <button className="gest_bton_popup" onClick={(event) => {
                                             handleClick_delete(event, cellValues);
                                             //console.log('modal closed ');
                                             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>
 
 
                 );
             }
            */} 

    ]



    const myRef = useRef(null)


    const myRef_head = useRef(null);
    const [selected_id, setselected_id] = useState("");

    const [Get_List_Agenda_Events_For_Given_User_api, setGet_List_Agenda_Events_For_Given_User_api] = useState();
    const [Get_List_Agenda_Events_For_Given_User_message, setGet_List_Agenda_Events_For_Given_User_message] = useState();
    const [Get_List_Agenda_Events_For_Given_User_result, setGet_List_Agenda_Events_For_Given_User_result] = useState();
    function Get_List_Agenda_Events_For_Given_User(local_selected_id) {

        var local_related_collection = p_filtre1;


        var form = new FormData();
        const stored_cookie = getCookie('tokenmysypart');

        form.append("token", stored_cookie);
        form.append("related_collection", local_related_collection);
        form.append("related_collection_recid", local_selected_id);



        var myurl = process.env.REACT_APP_API_URL + "myclass/api/get_Agenda_Event_List/";

        setLoading(true);

        axios.post(myurl, form).then(res => {
            //console.log(" In Get_List_Agenda_Events_For_Given_User  res.data.status = " + res.data.status);
            //console.log(" In Get_List_Agenda_Events_For_Given_User  res.data.message r_class = " + res.data.message);
            setLoading(false);
            if (String(res.data.status) === String("true")) {
                setGet_List_Agenda_Events_For_Given_User_api("true");
                setGet_List_Agenda_Events_For_Given_User_result(res.data.message);

                var tab_event = []
                var filtre2 = res.data.message.map(obj => {

                    var local_val = {}
                    if (JSON.parse(obj).comment) {
                        local_val = {
                            'title': String(JSON.parse(obj).event_title),
                            'start': String(JSON.parse(obj).event_start),
                            'end': String(JSON.parse(obj).event_end),
                            'id': String(JSON.parse(obj)._id),
                            'comment': String(JSON.parse(obj).comment),
                        }
                    } else {
                        local_val = {
                            'title': String(JSON.parse(obj).event_title),
                            'start': String(JSON.parse(obj).event_start),
                            'end': String(JSON.parse(obj).event_end),
                            'id': String(JSON.parse(obj)._id),
                            'comment': "",
                        }

                    }
                    tab_event.push(local_val);



                });
                setmysy_events(tab_event);


            }
            else if (String(res.data.status) === String("Err_Connexion")) {
                alert('Erreur: ' + res.data.message);
                history.push("/Connexion");
            }
            else {
                setGet_List_Agenda_Events_For_Given_User_api("false");
                setGet_List_Agenda_Events_For_Given_User_message(res.data.message);
            }

        }).catch((error) => {
            setLoading(false);
            console.warn('Not good man :( Get_List_Agenda_Events_For_Given_User = ', error);
            setGet_List_Agenda_Events_For_Given_User_api("false");
            //setmyApimyApiMessage("")
        })
    }


    useEffect(() => {

        Get_List_Agenda_Events_For_Given_User(selected_employee_id);
       
        if (document.getElementById('myRef_head')) {
            var divh = document.getElementById('myRef_head').offsetTop;
            window.scrollTo({
                top: divh,
                behavior: "smooth",
            });
        }
    }, [])


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

            <Dialog
                open={Dialog_1_open}
                onClose={Dialog_1_handleClose}

                className="module_absence"

            >

                <DialogTitle>MySy Information</DialogTitle>
                <DialogContent className="DialogContent_width">
                    <DialogContentText>
                        {Dialog_1_message}
                    </DialogContentText>

                    <div className="session_caract_Dialog" > Titre
                        <TextField
                            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}

                            name="event_dialog_title"
                            id="event_dialog_title"


                            fullWidth

                            value={p_detail_title}
                            onChange={(e) => {
                                if (String(props.write_access) === "1")
                                    setp_detail_title(e.target.value);
                            }
                            }

                        />

                    </div>

                    <div className="session_caract_Dialog" > Debut
                        <DatePicker
                            name="event_dialog_start"
                            id="event_dialog_start"
                            selected={startDate}
                            onChange={(date) => {
                                if (String(props.write_access) === "1")
                                    return setStartDate(date);
                            }
                            }

                           
                            className="disabled_style enable_style"
                            locale='fr-FR'
                            showTimeSelect
                            timeFormat="HH:mm"
                            timeIntervals={15}
                            dateFormat="dd/MM/yyyy HH:mm"
                            is24Hour

                        />

                    </div>


                    <div className="session_caract_Dialog" > Fin
                        <DatePicker
                            name="event_dialog_end"
                            id="event_dialog_end"
                            selected={endDate}

                            onChange={(date) => {
                                if (String(props.write_access) === "1")
                                    return setendDate(date);
                            }
                            }

                           
                            className="disabled_style enable_style"
                            locale='fr-FR'
                            showTimeSelect
                            timeFormat="HH:mm"
                            timeIntervals={15}
                            dateFormat="dd/MM/yyyy HH:mm"
                            is24Hour

                        />

                    </div>

                    <div className="session_caract_Dialog_comment_2_lines" > Commentaire
                        <TextField
                            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 }, }}

                            name="event_dialog_comment"
                            id="event_dialog_comment"

                            fullWidth

                            value={p_detail_comment}
                            onChange={(e) => {
                                if (String(props.write_access) === "1")
                                    setp_detail_comment(e.target.value);
                            }
                            }
                            multiline
                            minRows={2}
                            maxRows={2}
                            rows={2}

                        />

                    </div>


                </DialogContent>



                <DialogActions>
                    <div className="div_row">
                        {String(props.write_access) === "1" && <div className="div_row_gauche">
                            {p_detail_event_id && String(p_detail_event_id) !== "" && <Button onClick={Update_One_Agenda_Event} className="bton_enreg_dialog">Mettre à jour</Button>}
                            {(!p_detail_event_id || String(p_detail_event_id) === "") && <Button onClick={Update_One_Agenda_Event} className="bton_enreg_dialog">Ajouter</Button>}



                        </div>}
                        <div className="div_row_droite" style={{ "textAlign": 'center' }}>
                            <Button onClick={Close_Dialog_Detail_Event_open} className="bton_annule_dialog" >Fermer</Button>
                        </div>
                    </div>

                </DialogActions>




                {String(props.write_access) === "1" && p_detail_event_id && String(p_detail_event_id) !== "" && <DialogActions>
                    <div className="div_row" style={{ "textAlign": "center" }}>
                        <Button onClick={(e) => {
                            const response = window.confirm("Confirmez-vous la suppression de l'événement ?");
                            if (!response) {
                                return;
                            }
                            Delete_One_Agenda_Event();
                        }
                        } className="bton_supprime_dialog">Supprimer l'événement</Button>
                    </div>


                </DialogActions>}

            </Dialog>

            <h3> Absence </h3>
            <div className="div_row">
                <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="config_name" style={{ "paddingLeft": "5px", "textAlign": "left", "width": "100%" }} >Nom du point de configuration &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 id="my-tooltip01" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip01" data-tooltip-content="Ajouter une nouvelle ligne de filtre">
                            &nbsp; <MdAddCircleOutline onClick={(e) => {
                                setp_filtre2("1");
                                setp_filtre2_value("");
                            }} />
                        </a>
                    </div>}
                    {p_filtre1 && <div className='filter_bton_add'>
                        <Tooltip id="my-tooltip02" style={{ "fontSize": "12px" }} />
                        <a data-tooltip-id="my-tooltip02" data-tooltip-content="Supprimer cette ligne de filtre">
                            &nbsp; <MdRemoveCircleOutline onClick={(e) => {
                                setp_filtre1();
                                setp_filtre1_value();
                            }}
                            />
                        </a>
                    </div>}


                </div>

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

                    <div className="div_row_gauche" style={{ "textAlign": 'left', 'marginLeft': '15px' }}>
                        <Button variant="contained" className="bton_enreg" onClick={"Getall_Parter_Invoice_With_Filter"}>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>

                <br />
            </div>

            <div className="div_row">
                <div className="session_data">
                    <div style={{ "border": "None" }}>

                        <div style={{ height: 550, width: '100%', paddingRight: '1px' }}>
                            &nbsp;
                            <Box
                                sx={{
                                    height: 500,
                                    width: '100%',
                                    paddingRight: '1px',

                                    // Gestion des cellule "statut"
                                    '& .cell--status--encours': {
                                        backgroundColor: '#E6F7C8',
                                        color: '#1a3e72',
                                        fontWeight: 'light',
                                    },
                                    '& .cell--status--traite': {
                                        backgroundColor: '#E6CEAA',
                                        color: '#F9E79F',
                                        fontWeight: 'light',
                                    },




                                    /*"& .MuiDataGrid-virtualScrollerRenderZone": {
                                        "& .MuiDataGrid-row": {
                                            "&:nth-child(2n)": { backgroundColor: "rgba(235, 235, 235, .7)" }
                                        }
                                    },*/
                                    "& .MuiDataGrid-columnHeaders": {
                                        backgroundColor: "#c8cfd5",
                                        color: "black",
                                        fontSize: 14
                                    },

                                }}
                            >
                                <DataGrid
                                    checkboxSelection
                                    onSelectionModelChange={(newSelectionModel) => {
                                        setSelectionModel(newSelectionModel);
                                        /* if (newSelectionModel.length === 1)
                                             handleClick_edit_config_From_Line(newSelectionModel);
                                         if (newSelectionModel.length !== 1) {
                                             setp_detail_config_valeur();
                                             setp_detail_config_point();
                                             setConfig_data_changed();
                                             setconfig_data_edit_mode();
                                             setdisplay_detail_config();
 
 
                                         }*/
                                    }}
                                    selectionModel={selectionModel}

                                    localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                                    rows={rowss.map((item, index) => (
                                        {
                                            id: index,
                                            _id: JSON.parse(item)._id,
                                            config_name: JSON.parse(item).session_step_name,
                                            config_value: JSON.parse(item).session_step_sequence,
                                            config_comment: JSON.parse(item).session_step_comment,
                                        }
                                    ))}

                                    columns={columns}
                                    pageSize={10}
                                    className="datagridclass"

                                    onRowDoubleClick={(newSelectionModel) => {
                                        handleClick_edit_config_From_Line(newSelectionModel.row.id);

                                    }}

                                    rowsPerPageOptions={[10]}
                                    //disableSelectionOnClick
                                    components={{
                                        Toolbar: GridToolbar,
                                    }}
                                    //sx={datagridSx}
                                    getCellClassName={(params) => {


                                        //field === "order_header_status"
                                        if (params.field === "order_header_status" && String(params.value) == "0") {
                                            return 'cell--status--brouillon';
                                        }

                                        if (params.field === "order_header_status" && String(params.value) == "1") {

                                            return 'cell--status--encours';
                                        }

                                        if (params.field === "order_header_status" && String(params.value) == "2") {
                                            return 'cell--status--traite';
                                        }

                                        if (params.field === "order_header_status" && String(params.value) == "3") {
                                            return 'cell--status--facture';
                                        }

                                    }}
                                    getRowClassName={(params) => {

                                        if (String(params.row.status) === "-1") {
                                            return 'line--statut--annule';
                                        }
                                        if (String(params.row.status) === "0") {
                                            return 'line--statut--preinscrit';
                                        }
                                        if (String(params.row.status) === "1") {
                                            return 'line--statut--inscrit';
                                        }
                                    }}


                                />
                            </Box>
                            <br />

                        </div>

                    </div>

                </div>
                <div className="div_row" style={{ "border": "None" }}>

                    <div className="div_row_gauche div_row_gauche_etendu" style={{ "textAlign": "left", "paddingLeft": "5px" }}>
                        <Button variant="outlined" onClick={"submenu_add_one_step"}
                            className="detail_class_submenu bton_add_session"
                            id='menu_import_participant' name='menu_import_participant'>Ajout une étape &nbsp;
                            <img src={add_plus} alt="ajout commande" className="icon_plus" />
                        </Button>
                    </div>
                </div>
                <div className="div_row" ref={myRef} id="myRef"> &nbsp;</div>
            </div>




            </div>
    )
}


export default Module_Absence;