import React, { useRef, useState, useEffect } from "react";

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 { gridClasses } from '@mui/x-data-grid';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import Box from '@mui/material/Box';

import 'react-tooltip/dist/react-tooltip.css'
import { FcCancel, FcApproval, FcAcceptDatabase, } from "react-icons/fc";
import 'reactjs-popup/dist/index.css';
import img_loading_spin from "./../mysy_img/mysy_spin_loading.gif";
import { CiTrash } from "react-icons/ci";
import "react-datepicker/dist/react-datepicker.css";
import { DataGrid, GridToolbar, frFR } from '@mui/x-data-grid';
import { useParams } from 'react-router-dom'


import { FcCheckmark } from "react-icons/fc";

import Link from '@mui/material/Link';
import { PiDotsThree } from "react-icons/pi";
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import TextField from '@mui/material/TextField';
import Display_Action_And_Class from "./Display_Action_And_Class";

import Module_Alert_Confirmation from "./Module_Alert_Confirmation";
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
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 { IconButton } from '@material-ui/core';
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';

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',
    },
}));


function UpdateAttendeeList() {
    const classes = useStyles();
    const history = useHistory();
    const { client_id, session_id, partner_owner_recid } = useParams();
    const [isLoading, setLoading] = useState();

    const [tab_variable, settab_variable] = 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 : String(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>
        );
    }

    const [rowss_preinsc, setRows_preinsc] = useState([]);

 
    const [selectionModel_preinsc, setselectionModel_preinsc] = React.useState([]);
    const columns_preinscrit = [
        { field: 'id', headerName: 'id', hide: true },
        { field: '_id', headerName: '_id', hide: true },

        {
            field: 'civilite', headerName: 'Civ.', minWidth: 100, flex: 1, maxWidth: 100, hide: false, editable: true,
            type: "singleSelect",
            valueOptions: [
                { value: 'm', label: 'M' },
                { value: 'mme', label: 'Mme' },
                { value: 'neutre', label: 'Neutre' }
            ],
            renderCell: (params) => {
                return (

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

                        {params.value && String(params.value) === "m" && "M"}
                        {params.value && String(params.value) === "mme" && "Mme"}
                        {params.value && String(params.value) === "neutre" && "Neutre"}

                    </div>

                );
            }
        },

        { field: 'nom', headerName: 'nom', minWidth: 150, flex: 1, hide: false, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'prenom', headerName: 'prenom', minWidth: 150, flex: 1, hide: false, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'email', headerName: 'email', minWidth: 150, flex: 1, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },

        {
            field: 'status', headerName: 'Statut', minWidth: 150, flex: 1, editable: false,
            renderCell: (cellValues) => {
                return (
                    <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>

                        {cellValues.row.status && String(cellValues.row.status) === "1" && "Validé"}
                        {cellValues.row.status && String(cellValues.row.status) === "0" && "PréIns"}
                        {cellValues.row.pres_dist_hyp && String(cellValues.row.status) !== "0"
                            && String(cellValues.row.status) === "1" && "N/A"}
                    </div>

                );
            }
        },


    ]


    const columns_preinscrit_with_add_delete_bton = [
        { field: 'id', headerName: 'id', hide: true },
        { field: '_id', headerName: '_id', hide: true },

        {
            field: 'civilite', headerName: 'Civ.', minWidth: 100, flex: 1, maxWidth: 100, hide: false, editable: true,
            type: "singleSelect",
            valueOptions: [
                { value: 'm', label: 'M' },
                { value: 'mme', label: 'Mme' },
                { value: 'neutre', label: 'Neutre' }
            ],
            renderCell: (params) => {
                return (

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

                        {params.value && String(params.value) === "m" && "M"}
                        {params.value && String(params.value) === "mme" && "Mme"}
                        {params.value && String(params.value) === "neutre" && "Neutre"}

                    </div>

                );
            }
        },

        { field: 'nom', headerName: 'nom', minWidth: 150, flex: 1, hide: false, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'prenom', headerName: 'prenom', minWidth: 150, flex: 1, hide: false, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        { field: 'email', headerName: 'email', minWidth: 150, flex: 1, editable: true, renderCell: (params) => <ExpandableCell_50 {...params} />, },
        {
            field: 'status', headerName: 'Statut', minWidth: 150, flex: 1, editable: false,
            renderCell: (cellValues) => {
                return (
                    <div style={{ paddingLeft: "5px", paddingRight: "15px", "display": "block", wordBreak: "break-all" }}>

                        {cellValues.row.status && String(cellValues.row.status) === "1" && "Validé"}
                        {cellValues.row.status && String(cellValues.row.status) === "0" && "PréIns"}
                        {cellValues.row.pres_dist_hyp && String(cellValues.row.status) !== "0"
                            && String(cellValues.row.status) === "1" && "N/A"}
                    </div>

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

                        {cellValues.row.status === "1" && <Button onClick={(event) => {
                            setdisplay_alert_mysy("1");
                            setalert_message("Cette inscription est déjà validée");
                            setalert_type("info");
                            return;
                        }}>
                            <FcCheckmark />
                        </Button>}

                        {cellValues.row.status === "0" && <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, la ligne 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) => {
                                                delete_data_grid_line(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>}

                    </div>


                );
            }
        },

    ]


    const [document_checked, setdocument_checked] = useState("0");

    const [Getall_Client_Communication_Contact_api, setGetall_Client_Communication_Contact_api] = useState();
    const [Getall_Client_Communication_Contact_message, setGetall_Client_Communication_Contact_message] = useState();
    const [Getall_Client_Communication_Contact_result, setGetall_Client_Communication_Contact_result] = useState([]);
    function Getall_Client_Communication_Contact(event) {

        var form = new FormData();

        form.append("_id", client_id);
        form.append("partner_owner_recid", partner_owner_recid);

        //console.log(" ### Getall_Client_Communication_Contact form = ", form)
        var myurl = process.env.REACT_APP_API_URL + "myclass/api/Get_Partner_Client_Communication_Contact_NO_TOKEN/";


        setLoading(true);
        axios.post(myurl, form).then(res => {


            setLoading(false);
            if (String(res.data.status) === String("true")) {
                //console.log(" In Getall_Client_Communication_Contact  res.data.status = " + res.data.status);
                //console.log(" In Getall_Client_Communication_Contact  res.data.message r_class = " + res.data.message);
                setGetall_Client_Communication_Contact_api("true");
                setGetall_Client_Communication_Contact_result(res.data.message);
                setdocument_checked("1");

            }
            else {
                setGetall_Client_Communication_Contact_api("false");
                setGetall_Client_Communication_Contact_message(res.data.message);
                // alert(res.data.message);
                setdisplay_alert_mysy("1");
                setalert_message(res.data.message);
                setalert_type("error");
                setdocument_checked("1");

            }

        }).catch((error) => {
            setLoading(false);
            console.warn('Not good man :( Getall_Client_Communication_Contact = ', error);
            setGetall_Client_Communication_Contact_api("false");
            alert(" Impossible de recuperer la liste des stagiaires")
            setdocument_checked("1");

            //setmyApimyApiMessage("")
        })
    }


    const [Partner_Recid, setPartner_Recid] = useState("");
    const [class_internal_url, setclass_internal_url] = useState("");
    const [max_presinscrit, setmax_presinscrit] = useState("");
    const [is_client_preinsc_update_request, setis_client_preinsc_update_request] = useState("");



    const [New_Getall_TrainingParticipant_result, setNew_Getall_TrainingParticipant_result] = useState([]);

    const [Getall_TrainingParticipant_api, setGetall_TrainingParticipant_api] = useState();
    const [Getall_TrainingParticipant_message, setGetall_TrainingParticipant_message] = useState();
    const [Getall_TrainingParticipant_result, setGetall_TrainingParticipant_result] = useState([]);
    function Getall_TrainingParticipant(event) {

        var form = new FormData();

        form.append("client_rattachement_id", client_id);
        form.append("session_id", session_id);
        form.append("partner_owner_recid", partner_owner_recid);
        form.append("status", "0");

        //console.log(" ### Getall_TrainingParticipant form = ", form)
        var myurl = process.env.REACT_APP_API_URL + "myclass/api/Get_Statgaire_List_Partner_with_filter_FOR_ONLY_INSCRIPTION_NO_TOKEN/";


        setLoading(true);
        axios.post(myurl, form).then(res => {

            setLoading(false);
            if (String(res.data.status) === String("true")) {
                //console.log(" In Getall_TrainingParticipant  res.data.status = " + res.data.status);
                //console.log(" In Getall_TrainingParticipant  res.data.message r_class = " + res.data.message, " -- message_global_data = ", res.data.message_global_data);
                setGetall_TrainingParticipant_api("true");
                setGetall_TrainingParticipant_result(res.data.message);
                setRows_preinsc(res.data.message);

                setmax_presinscrit(String(JSON.parse(res.data.message_global_data).max_presinscrit))
                setis_client_preinsc_update_request(String(JSON.parse(res.data.message_global_data).is_client_preinsc_update_request))



                var new_data2 = [];
                const new_data = res.data.message.map((x) => {
                    //---
                    var localid = JSON.parse(x).id;
                    var local_id = JSON.parse(x)._id;
                    var local_status = JSON.parse(x).status;
                    var local_nom = JSON.parse(x).nom;
                    var local_prenom = JSON.parse(x).prenom;
                    var local_email = JSON.parse(x).email;
                    var local_civilite = JSON.parse(x).civilite;

                    setPartner_Recid(String(JSON.parse(x).partner_owner_recid));
                    setclass_internal_url(String(JSON.parse(x).class_internal_url));

                    //---
                    var node = {
                        "_id": local_id,
                        "id": localid,
                        "nom": local_nom,
                        "prenom": local_prenom,
                        "email": local_email,
                        "civilite": local_civilite,
                        "status": local_status,
                    };
                    new_data2.push(node);

                    // return {"_id": " + str(local_id) + ", "label": " + local_courrier_template_ref_interne + '" , "courrier_template_ref_interne": "' + local_courrier_template_ref_interne + '", "nom_champ_technique": "' + local_nom_champ_technique + '",  "nom_champ_fonctionel": "' + local_nom_champ_fonctionel + '","valide": "1" };

                });


                if (new_data2.length > 0) {
                    setNew_Getall_TrainingParticipant_result(new_data2);
                }

            }
            else {
                setGetall_TrainingParticipant_api("false");
                setGetall_TrainingParticipant_message(res.data.message);
                // alert(res.data.message);
                setdisplay_alert_mysy("1");
                setalert_message(res.data.message);
                setalert_type("error");
            }

        }).catch((error) => {
            setLoading(false);
            console.warn('Not good man :( Getall_TrainingParticipant = ', error);
            setGetall_TrainingParticipant_api("false");
            alert(" Impossible de recuperer la liste des stagiaires")
            //setmyApimyApiMessage("")
        })
    }

    useEffect(() => {

        Getall_TrainingParticipant();

        Getall_Client_Communication_Contact();
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });
    }, [])


    function OnchangeCellDataGrid(params) {


        // params = la nouvelle lignes


        var num_line = params.id;  // ==> Id de la ligne changé
        var colomn = params.field; // ==> colonne de la ligne changé
        var new_value = params.value; // ==> la nouvelle valeur



        const updatedData = New_Getall_TrainingParticipant_result.map((x) => {

            var localid = (x).id;

            if (String(num_line) === String(localid) && colomn === "nom") {
                var tmp = {};
                tmp['id'] = (x).id;
                tmp['_id'] = (x)._id;
                tmp['nom'] = new_value;
                tmp['prenom'] = (x).prenom;
                tmp['email'] = (x).email;
                tmp['civilite'] = (x).civilite;
                tmp['status'] = (x).status;
                return tmp;


            }

            if (String(num_line) === String(localid) && colomn === "prenom") {
                var tmp = {};
                tmp['id'] = (x).id;
                tmp['_id'] = (x)._id;
                tmp['nom'] = (x).nom;
                tmp['prenom'] = new_value;
                tmp['email'] = (x).email;
                tmp['civilite'] = (x).civilite;
                tmp['status'] = (x).status;

                return tmp;
            }

            if (String(num_line) === String(localid) && colomn === "civilite") {
                var tmp = {};
                tmp['id'] = (x).id;
                tmp['_id'] = (x)._id;
                tmp['nom'] = (x).nom;
                tmp['prenom'] = (x).prenom;
                tmp['email'] = (x).email;
                tmp['civilite'] = new_value;
                tmp['status'] = (x).status;

                return tmp;
            }

            if (String(num_line) === String(localid) && colomn === "email") {
                var tmp = {};
                tmp['id'] = (x).id;
                tmp['_id'] = (x)._id;
                tmp['nom'] = (x).nom;
                tmp['prenom'] = (x).prenom;
                tmp['email'] = new_value;
                tmp['civilite'] = (x).civilite;
                tmp['status'] = (x).status;

                return tmp;
            }


            var tmp = {};
            tmp['id'] = (x).id;
            tmp['_id'] = (x)._id;
            tmp['nom'] = (x).nom;
            tmp['prenom'] = (x).prenom;
            tmp['email'] = (x).email;
            tmp['civilite'] = (x).civilite;
            tmp['status'] = (x).status;

            return tmp;


        });

        //     console.log(" ### updatedData = ", updatedData);

        setNew_Getall_TrainingParticipant_result([]);

        setNew_Getall_TrainingParticipant_result(updatedData);

    }



    const [Record_New_Attendee_Data_api, setRecord_New_Attendee_Data_api] = useState();
    const [Record_New_Attendee_Data_message, setRecord_New_Attendee_Data_message] = useState();
    const [Record_New_Attendee_Data_result, setRecord_New_Attendee_Data_result] = useState([]);
    function Record_New_Attendee_Data() {
        var form = new FormData();

        const myJSON = JSON.stringify(tab_variable);



        const new_attende_dat_JSON = JSON.stringify(New_Getall_TrainingParticipant_result);

        // console.log(" Record_New_Attendee_Data New_Getall_TrainingParticipant_result = ", New_Getall_TrainingParticipant_result);

        const stored_cookie = getCookie('tokenmysypart');
        form.append("client_id", client_id);
        form.append("session_id", session_id);
        form.append("list_attendee_data", new_attende_dat_JSON);
        form.append("partner_recid", Partner_Recid);
        form.append("is_client_preinsc_update_request", is_client_preinsc_update_request);

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

        setLoading(true);
        axios.post(myurl, form).then(res => {
            //   console.log(" In Record_New_Attendee_Data  res.data.status = " + res.data.status);
            //  console.log(" In Record_New_Attendee_Data  res.data.message r_class = " + res.data.message);

            setLoading(false);
            if (String(res.data.status) === String("true")) {

                // alert(res.data.message);
                setdisplay_alert_mysy("1");
                setalert_message(res.data.message);
                setalert_type("success");

                Getall_TrainingParticipant();

                //history.push("/");
            }
            else {
                setRecord_New_Attendee_Data_api("false");
                setRecord_New_Attendee_Data_message(res.data.message);
                // alert(res.data.message);
                setdisplay_alert_mysy("1");
                setalert_message(res.data.message);
                setalert_type("error");
            }

        }).catch((error) => {
            setLoading(false);
            console.warn('Record_New_Attendee_Data : Not good man :( Record_New_Attendee_Data = ' + error);
            setRecord_New_Attendee_Data_api("false");
            alert(" Impossible de mettre à jour les données des participants ");

        })
    }

    const [display_alert_mysy, setdisplay_alert_mysy] = useState("");
    const [alert_message, setalert_message] = useState("");
    const [alert_type, setalert_type] = useState("");

    function clear_alert_message() {
        setalert_message("");
    }
    function clear_alert_type() {
        setalert_type("");
    }
    function clear_display_alert_mysy() {
        setdisplay_alert_mysy("");
    }

    function add_one_ligne_to_datagrid() {

        if (New_Getall_TrainingParticipant_result.length >= String(max_presinscrit)) {
            setdisplay_alert_mysy("1");
            setalert_message("Vous avez atteint le nombre maximum d'inscriptions autorisé");
            setalert_type("warning");
            return;
        }

        if (String(is_client_preinsc_update_request) === "1" && New_Getall_TrainingParticipant_result.length < String(max_presinscrit)) {
            var new_data2 = [];
            const new_data = New_Getall_TrainingParticipant_result.map((x) => {
                //---
                var localid = (x).id;
                var local_id = (x)._id;
                var local_nom = (x).nom;
                var local_prenom = (x).prenom;
                var local_email = (x).email;
                var local_civilite = (x).civilite;
                var local_status = (x).status;


                //---
                var node = {
                    "_id": local_id,
                    "id": localid,
                    "nom": local_nom,
                    "prenom": local_prenom,
                    "email": local_email,
                    "civilite": local_civilite,
                    "status": local_status,
                };
                new_data2.push(node);

            });

            //---
            var node = {
                "_id": "new",
                "id": String(New_Getall_TrainingParticipant_result.length),
                "nom": "new_nom",
                "prenom": "new_prenom",
                "email": "new_email@email.com",
                "civilite": "neutre",
                "status": "0",
            };
            new_data2.push(node);

            if (new_data2.length > 0) {
                setNew_Getall_TrainingParticipant_result(new_data2);
            }

        }

    }

    function delete_data_grid_line(event, cellValues) {

        if (cellValues.row.status !== "0") {
            setdisplay_alert_mysy("1");
            setalert_message("Le statut soit être à 'Preins' pour être supprimable. Merci de contacter le gestionnaire de formation");
            setalert_type("warning");
            return;
        }



        if (String(is_client_preinsc_update_request) === "1" && New_Getall_TrainingParticipant_result.length <= String(max_presinscrit)) {
            var new_data2 = [];
            const new_data = New_Getall_TrainingParticipant_result.map((x) => {

                if ((x).id != cellValues.row.id) {
                    //---
                    var localid = (x).id;
                    var local_id = (x)._id;
                    var local_nom = (x).nom;
                    var local_prenom = (x).prenom;
                    var local_email = (x).email;
                    var local_civilite = (x).civilite;
                    var local_status = (x).status;



                    //---
                    var node = {
                        "_id": local_id,
                        "id": localid,
                        "nom": local_nom,
                        "prenom": local_prenom,
                        "email": local_email,
                        "civilite": local_civilite,
                        "status": local_status,
                    };
                    new_data2.push(node);
                }

            });

            // Si le tableau est vide de chez vide, on ajoute une ligne
            if (new_data2.length <= 0) {
                var node = {
                    "_id": "new",
                    "id": String(New_Getall_TrainingParticipant_result.length),
                    "nom": "new_nom",
                    "prenom": "new_prenom",
                    "email": "new_email@email.com",
                    "civilite": "neutre",
                    "status": "0",
                };
                new_data2.push(node);
            }


            setNew_Getall_TrainingParticipant_result(new_data2);
            var form = new FormData();

            const myJSON = JSON.stringify(tab_variable);



            const new_attende_dat_JSON = JSON.stringify(New_Getall_TrainingParticipant_result);

            // console.log(" Record_New_Attendee_Data New_Getall_TrainingParticipant_result = ", New_Getall_TrainingParticipant_result);

            const stored_cookie = getCookie('tokenmysypart');
            form.append("client_id", client_id);
            form.append("session_id", session_id);
            form.append("partner_recid", Partner_Recid);
            form.append("inscription_id", cellValues.row._id);

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

            setLoading(true);
            axios.post(myurl, form).then(res => {
                //   console.log(" In Record_New_Attendee_Data  res.data.status = " + res.data.status);
                //  console.log(" In Record_New_Attendee_Data  res.data.message r_class = " + res.data.message);

                setLoading(false);
                if (String(res.data.status) === String("true")) {

                    // alert(res.data.message);
                    setdisplay_alert_mysy("1");
                    setalert_message(res.data.message);
                    setalert_type("success");

                    Getall_TrainingParticipant();

                    //history.push("/");
                }
                else {
                    setRecord_New_Attendee_Data_api("false");
                    setRecord_New_Attendee_Data_message(res.data.message);
                    // alert(res.data.message);
                    setdisplay_alert_mysy("1");
                    setalert_message(res.data.message);
                    setalert_type("error");
                }

            }).catch((error) => {
                setLoading(false);
                console.warn('delete_data_grid_line : Not good man :( delete_data_grid_line = ' + error);
                setRecord_New_Attendee_Data_api("false");
                alert(" Impossible de supprimer le participant ");

            })


        }


    }

    const [Dialog_preinscrit_message, setDialog_preinscrit_message] = React.useState(false);
    const [Dialog_preinscrit_open, setDialog_preinscrit_open] = React.useState(false);
    function Dialog_preinscrit_handle_change_participant_session(message) {
        setDialog_preinscrit_message(message);
        setDialog_preinscrit_open(true);
    }

    const Dialog_preinscrit_handleClose = () => {
        //alert(" Utiliser le bouton 'fermer' ");
        //setOpen(false);
    };

    const Dialog_preinscrit_handleClose_buton = () => {

        setDialog_preinscrit_open(false);
    };
    const [Dialog_1_message, setDialog_1_message] = React.useState(false);

    return (
        <div className="updateattendeelist">


            {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*/}



            {/*  Dialog pour gerer Un PRE/INSCRIT */}
            <Dialog
                open={Dialog_preinscrit_open}
                // onClose={Dialog_preinscrit_handleClose}
                //className="displaypartnersession"

                className="displaypartnersession"

                static
                onClose={() => null}

                PaperProps={{


                    className: classes.paper, // Apply the paper style
                    style: {
                        overflowY: 'unset',
                        position: 'absolute',
                        top: '7rem',
                        margin: "2px",
                    },
                }}
                hideBackdrop={true}
                disableScrollLock
                classes={{
                    paper: classes.dialog
                }}

                PaperComponent={PaperComponent}
                aria-labelledby="draggable-dialog-title"

            >
                <DialogTitle style={{ cursor: 'move', fontFamily:"DM Sans"}} id="draggable-dialog-title"> Apprenant </DialogTitle>
                <DialogContent className="DialogContent_width" style={{ "minHeight": "20rem" }}>
                    <DialogContentText>
                        {Dialog_1_message}
                    </DialogContentText>


                    <div className="session_caract_Dialog">Etape <br />

                        {/*<Autocomplete
                            disablePortalNew
                            name="duplicate_session_etape"
                            id="duplicate_session_etape"
                            className="disabled_style"
                            options={New_Getall_Parter_OR_Default_Session_Steps_result}
                            value={New_Getall_Parter_OR_Default_Session_Steps_result.filter((data) => (data).session_step_name === String(dup_p_session_etape))[0].session_step_name}

                            onChange={(event, value) => {
                                if (value && value.session_step_name) {
                                    setdup_p_session_etape(value.session_step_name);

                                } else {
                                    setdup_p_session_etape("");
                                }
                            }}

                            renderInput={(params) => <TextField {...params} label="" placeholder="Choisir une option"
                                inputProps={{ ...params.inputProps, style: { fontSize: 12, height: "1.4rem" } }}

                            />
                            }
                        />*/}



                    </div>


                    {/*

                    <div className="session_caract_Dialog" > Date Session<br />
                        <div style={{ width: "45%", float: "left", textAlign: "left" }}>
                            <DatePicker
                                name="date_du"
                                id="date_du"
                                selected={new Date(moment(dup_p_date_du, "DD/MM/YYYY"))}
                                onChange={(date) => {
                                    setdup_p_date_du(format(date, 'd/MM/yyyy'));

                                }
                                }
                                showTimeSelect={false}
                                dateFormat="dd/MM/yyyy"
                                className="disabled_style enable_style datepicker_complement"
                                locale='fr-FR'

                            />

                        </div>
                        <div style={{ float: "left", textAlign: "center", paddingTop: "20px", fontSize: "12px" }}>
                            Au

                        </div>
                        <div style={{ width: "45%", float: "left", textAlign: "right" }}>

                            <DatePicker
                                name="date_du"
                                id="date_du"
                                selected={new Date(moment(dup_p_date_au, "DD/MM/YYYY"))}
                                onChange={(date) => {
                                    setdup_p_date_au(format(date, 'd/MM/yyyy'));

                                }
                                }
                                showTimeSelect={false}
                                dateFormat="dd/MM/yyyy"
                                className="disabled_style enable_style datepicker_complement"
                                locale='fr-FR'

                            />
                        </div>

                    </div> */}

                </DialogContent>

                <DialogActions>

                    <IconButton
                        autoFocus
                        onClick={Dialog_preinscrit_handleClose_buton}
                        color="primary"
                        className={classes.customizedButton}
                    >
                        <CancelPresentationIcon />
                    </IconButton>


                    <div className="div_row">
                        <div className="div_row_gauche">
                            <Button onClick={(e) => {

                            }}
                                className="bton_enreg_dialog">Dupliquer </Button>

                        </div>


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

                </DialogActions>

            </Dialog>
            {/*  FIN Dialog pour gerer Un PRE/INSCRIT */}



            <div className="div_row">
                &nbsp;
            </div>

            {Getall_Client_Communication_Contact_result && Getall_Client_Communication_Contact_result.length > 0 &&
                <div className="div_row" style={{ "width": "90%", "marginLeft": "5%", "background": "white",
                    fontFamily:'DM Sans'
                 }}>
                    <div style={{ textAlign: 'left' }}>


                        <nav style={{ textAlign: 'left' }}>
                            <b>   Bonjour  {JSON.parse(Getall_Client_Communication_Contact_result).civilite}  {JSON.parse(Getall_Client_Communication_Contact_result).nom} </b>

                        </nav>


                        Merci de completer les informations des participants à session de formation ci-dessous. <br />
                    </div>
                    <br />
                    {Getall_TrainingParticipant_result && Getall_TrainingParticipant_result.length > 0 &&
                        <div style={{ textAlign: 'left' }}>
                            <b>  Formation :  </b>  {JSON.parse(Getall_TrainingParticipant_result[0]).title} <br />
                            <b>  Code Session :  </b>  {JSON.parse(Getall_TrainingParticipant_result[0]).title} <br />
                            <b>  Titre Session :  </b>  {JSON.parse(Getall_TrainingParticipant_result[0]).session_titre} <br />
                            <b>  Date début : </b>   {JSON.parse(Getall_TrainingParticipant_result[0]).date_du} <br />
                            <b>  Date fin : </b>  {JSON.parse(Getall_TrainingParticipant_result[0]).date_au} <br />

                        </div>
                    }

                    <br />
                </div>}

            <div className="div_row">
                &nbsp;
            </div>
            {String(is_client_preinsc_update_request) !== "1" && New_Getall_TrainingParticipant_result && New_Getall_TrainingParticipant_result.length > 0 && <div style={{ "width": "90%", "marginLeft": "5%", "background": "white", }}>


                <div className="session_data" >
                    <div style={{ height: 550, width: '100%', paddingRight: '5px' }}>
                        <Box
                            sx={{
                                height: 500,
                                width: '100%',
                                paddingRight: '2px',


                                [`& .${gridClasses.cell}`]: {
                                    py: 1,
                                },
                                '& .line--inscription--done': {
                                    backgroundColor: '#EAFAF1',
                                    color: '#239B56',
                                    fontWeight: '700'

                                },
                                "& .MuiDataGrid-columnHeaders": {
                                    backgroundColor: "#c8cfd5",
                                    color: "black",
                                    fontSize: 14
                                },


                            }}

                        >
                            <DataGrid

                                onCellEditCommit={OnchangeCellDataGrid}
                                editMode="cell"


                                checkboxSelection
                                onSelectionModelChange={(newSelectionModel) => {
                                    setselectionModel_preinsc(newSelectionModel);
                                    //console.log("ch selected--" + newSelectionModel);
                                }}
                                selectionModel={selectionModel_preinsc}

                                localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                                rows={New_Getall_TrainingParticipant_result.map((item, index) => (
                                    {
                                        id: index,
                                        _id: item._id,
                                        _id: item._id,
                                        nom: item.nom,
                                        prenom: (item).prenom,
                                        email: (item).email,
                                        civilite: (item).civilite,
                                        status: (item).status,
                                    }
                                ))}

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

                                rowsPerPageOptions={[10]}
                                disableSelectionOnClick
                                components={{
                                    Toolbar: GridToolbar,
                                }}

                                getRowClassName={(params) => {

                                    // Pour la gestion de la couleur de zone double cliquée
                                    if (String(params.row.status) === "1") {
                                        return 'line--inscription--done';
                                    }


                                }}

                                getEstimatedRowHeight={() => 200}
                                getRowHeight={() => "auto"}
                                sx={{
                                    "& .MuiDataGrid-cellContent": {
                                        minHeight: 50,

                                    },
                                    [`& .${gridClasses.cell}`]: {
                                        py: 1,
                                    },
                                }}
                            />
                        </Box>

                        <br />

                    </div>

                </div>
                <br />



            </div>}

            <div className="div_row">
                {String(is_client_preinsc_update_request) !== "1" && String(document_checked) === "1" && (!Getall_TrainingParticipant_result || Getall_TrainingParticipant_result.length <= 0) && <div style={{
                    height: "40vh", "width": "100%",
                    "background": "#F2F4F4", overflow: "auto", "paddingBottom": "1rem",
                    "marginTop": "5rem", "color": "red", fontWeight: '700', "fontSize": "20px"
                }}>

                    Le document est invalide

                </div>}

                {String(is_client_preinsc_update_request) === "1" && String(max_presinscrit) > "0" &&
                    <div>
                        <div className="div_row" style={{ "width": "90%", "marginLeft": "5%", "background": "white", "textAlign": 'left', "marginBottom": "2rem" }}>
                            <b> Inscrire ou mettre à jour les participants à la formation. Maxium autorisé :  {max_presinscrit} </b><br />
                            Procedure : <br />
                            Pour mettre à jour une cellule  : Double cliquer sur la cellule et modifier l'information. <br />
                            Pour ajouter ou supprimer une ligne : Utiliser les boutons.
                            <br />
                        </div>


                        {New_Getall_TrainingParticipant_result && New_Getall_TrainingParticipant_result.length > 0 && <div style={{ "width": "90%", "marginLeft": "5%", "background": "white", }}>

                            <div className="session_data" >
                                <div style={{ height: 550, width: '100%', paddingRight: '5px' }}>
                                    <Box
                                        sx={{
                                            height: 500,
                                            width: '100%',
                                            paddingRight: '2px',


                                            [`& .${gridClasses.cell}`]: {
                                                py: 1,
                                            },
                                            '& .line--inscription--done': {
                                                backgroundColor: '#EAFAF1',
                                                color: '#239B56',
                                                fontWeight: '700'

                                            },
                                            "& .MuiDataGrid-columnHeaders": {
                                                backgroundColor: "#c8cfd5",
                                                color: "black",
                                                fontSize: 14
                                            },


                                        }}

                                    >
                                        <DataGrid

                                            onCellEditCommit={OnchangeCellDataGrid}
                                            editMode="cell"


                                            checkboxSelection
                                            onSelectionModelChange={(newSelectionModel) => {
                                                setselectionModel_preinsc(newSelectionModel);
                                                //console.log("ch selected--" + newSelectionModel);
                                            }}
                                            selectionModel={selectionModel_preinsc}

                                            localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                                            rows={New_Getall_TrainingParticipant_result.map((item, index) => (
                                                {
                                                    id: index,
                                                    _id: item._id,
                                                    nom: item.nom,
                                                    prenom: (item).prenom,
                                                    email: (item).email,
                                                    civilite: (item).civilite,
                                                    status: (item).status,
                                                }
                                            ))}

                                            columns={columns_preinscrit_with_add_delete_bton}

                                            isCellEditable={(params) => params.row.status === "0"}

                                            pageSize={10}
                                            className="datagridclass"


                                            rowsPerPageOptions={[10]}
                                            disableSelectionOnClick
                                            components={{
                                                Toolbar: GridToolbar,
                                            }}

                                            getRowClassName={(params) => {

                                                // Pour la gestion de la couleur de zone double cliquée
                                                if (String(params.row.status) === "1") {
                                                    return 'line--inscription--done';
                                                }


                                            }}

                                            getEstimatedRowHeight={() => 200}
                                            getRowHeight={() => "auto"}
                                            sx={{
                                                "& .MuiDataGrid-cellContent": {
                                                    minHeight: 50,

                                                },
                                                [`& .${gridClasses.cell}`]: {
                                                    py: 1,
                                                },
                                            }}
                                        />
                                    </Box>

                                    <br />

                                </div>

                                <div className="div_row" style={{ "border": "None", marginBottom: "1rem" }}>
                                    <div className="div_row_gauche" style={{ "textAlign": 'left', 'marginLeft': '15px' }}>

                                        &nbsp;

                                    </div>

                                    <div className="div_row_droite" style={{ "textAlign": 'right', 'marginRight': '15px' }} >
                                        <nav style={{
                                            "textAlign": 'right', width: '15rem', color: '#1976d2',
                                            boxSizing: 'border-box', border: 'none', margin: 'auto', 'marginRight': '10px',
                                            'cursor': 'pointer'
                                        }} onClick={(event) => {
                                            add_one_ligne_to_datagrid();
                                        }}> <AddCircleOutlineIcon />1 ligne </nav>

                                    </div>

                                </div>

                            </div>
                            <br />

                        </div>}

                    </div>}

            </div>
            <br />
            <div className="div_row" style={{ width: '90%', marginLeft: '5%', marginTop: '1rem' }}>
                <div className="div_row_gauche" style={{ "textAlign": 'left', }}>

                    <Popup
                        trigger={

                            <Button variant="contained" className="bton_enreg" onClick={Record_New_Attendee_Data}>Mettre à jour
                            </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, les données des préinscrits seront mises à jour.


                                </div>
                                <div className="gest_actions">
                                    <div style={{ "width": "45%", "float": "left" }}>
                                        <button className="gest_bton_popup" onClick={(event) => {
                                            Record_New_Attendee_Data(event);
                                            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>


                </div>

                <div className="div_row_droite" style={{ "textAlign": 'right' }} >
                    <Button variant="contained" className="bton_annule" onClick={(event) => {
                        history.push("/");
                    }}  >Annuler
                    </Button>
                </div>
            </div>



            <div className="div_row">
                &nbsp;
            </div>

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

            <div style={{ "width": "100%", "background": "#F2F4F4", overflow: "auto", "paddingBottom": "1rem" }}>
                <br />

                {class_internal_url && String(class_internal_url).length > 2 && <div className="question_box_entete">
                    <Display_Action_And_Class classId={class_internal_url} action={""} />

                </div>}
            </div>


        </div>
    );
}

export default UpdateAttendeeList;