import React, { useState, useEffect } from "react";
import UpdateUserInfo from "../components/UpdateUserInfo";
import bannerimg from "../mysy_img/MYSY_banner_compte.png";
import profileimg from "../mysy_img/MYSY-profil-2.png";
import Button from '@mui/material/Button';
import { useHistory } from "react-router-dom";
import LogoutIcon from '@mui/icons-material/Logout';
import UserHistoryRecherche from "../components/UserHistoryRecherche";
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css'; // Import css
import { Helmet } from "react-helmet";
import { useCookies } from "react-cookie";
import bannerimg2 from "../mysy_img/MYSY-LOGO-BLUE.png";
import axios from "axios";
import { getCookie, removeCookie } from 'react-use-cookie';
import logowhite from "../mysy_img/MYSY-LOGO-WHITE.png";
import Footer from "./Fotter";
import Header from "./Header";
import UpgradeToPro from "./UpgradeToPro"
import Profil_Objectif from "./ProfilObjectif";
import { useLocation } from "react-router-dom";
import { FaHandPointRight } from "react-icons/fa";
import Intranet_Factures_Client from "./Intranet_Factures_Client";
import Intranet_Tous_Documents from "./Intranet_Tous_Documents";
import Modules_Mes_Documents from "./Modules_Mes_Documents";
import Intranet_Mes_Stagiaires from "./Intranet_Mes_Stagiaires";

function Account() {
    const [menu, setmenu] = useState("mes_stagiaires");
    const [cookie, setCookie, removeCookie] = useCookies(['tokenmysych']);
    const [result, setResult] = useState("");
    const [myApiResponse, setmyApiResponse] = useState("");
    const stored_user = getCookie('tokenmysych');
    const history = useHistory();
    const [country_code, setcountry_code] = useState("");
    const [country_name, setcountry_name] = useState("");
    const [city, setcity] = useState("");
    const [postal, setpostal] = useState("");
    const [latitude, setlatitude] = useState("");
    const [longitude, setlongitude] = useState("");
    const [IPv4, setIPv4] = useState("");
    const [state, setstate] = useState("");
    const [userimgprofil, setuserimgprofil] = useState();
    const [userIp, setuserIp] = useState("");
    const [username, setusername] = useState("");
    const [migratedaccount, setmigratedaccount] = useState("0");

    const apiUrl = process.env.REACT_APP_API_URL;
    const formData = new FormData();

    //alert("stored_user =  "+stored_user);
    const location = useLocation();
    useEffect(() => {

        var list_menu = ["affichage", "recherche", "upgradecompte", "profil_objectif", "mes_factures", "mes_documents"]

        getImage();

        if (typeof (stored_user) === "undefined" || String(stored_user) === '') {
            //alert(" début puch");
            history.push("/Connexion");
        }


        async function fetchData() {
            const result = await axios('https://geolocation-db.com/json/',);
            //alert(result.data.IPv4);
            setuserIp(result.data.IPv4);
            setcountry_code(result.data.country_code);
            setcountry_name(result.data.country_name);
            setcity(result.data.city);
            setpostal(result.data.postal);
            setlatitude(result.data.latitude);
            setlongitude(result.data.longitude);
            setIPv4(result.data.IPv4);
            setstate(result.data.state);
            setuserIp(result.data.IPv4);
        }
        GetUserNameFromToken();

        fetchData();


        if (location && location.state && location.state.menu) {
            displayProfil_Objectif();
        }

        if (location && location.state && location.state.firstconnexion) {
            setfirstConnexion(location.state.firstconnexion);
        }




    }, []);

    const [myimage, setmyimage] = useState();
    const [isimage, setisimage] = useState();

    function getImage(e) {
        var myurl = process.env.REACT_APP_API_URL + "myclass/api/getRecodedImage/";
        var form = new FormData();
        form.append("token", stored_user);
        form.append("type", "user");

        axios.post(myurl, form).then(res => {
            if (res.data.status != "False") {
                //console.log(" getImage : In test  res.data.status = " + res.data.status);
                //console.log(" getImage: res.data.message.img = " + res.data.message);
                if (res.data.message.img.length > 0) {
                    setisimage("True");
                }
                else {
                    setisimage("False");
                }
                setmyimage(res.data.message.img);
                var ch_img = "data:image/png;base64," + res.data.message.img;
                setuserimgprofil(ch_img);
            }
            else {
                //console.log(" In Erreur   res.data.status = " + res.data.status);
                //console.log(" In Erreur  res.data.message = " + res.data.message);
                setisimage("False");
                setuserimgprofil(profileimg);
            }
        }).catch((error) => {
            console.warn('Not good man :( mysearchtext = ');
            setisimage("False");
            setuserimgprofil(profileimg);
        })

    }

    const [firstConnexion, setfirstConnexion] = useState("");


    function logout_confirmation() {
        /* si c'est une connexion partner qui est active */
        if (typeof (stored_user) != "undefined") {
            removeCookie('tokenmysych', { path: '/' });
            history.push("/Connexion");
        }
    }

    function logout() {
        confirmAlert({
            title: 'Deconnexion ?',
            message: 'Confirmez la deconnexion',
            buttons: [
                {
                    label: 'Oui',
                    onClick: () => logout_confirmation()
                },
                {
                    label: 'Non',
                    onClick: () => { return }
                }
            ]
        });
    }


    const displayHistory = () => {
        setmenu("recherche");
    };


    const displayProfil_Objectif = () => {
        setmenu("profil_objectif");
    };


    const displayProfil_Facture = () => {
        setmenu("mes_factures");
    };

    const displayProfil_Devis = () => {
        setmenu("mes_devis");
    };

    const displayProfil_Convention = () => {
        setmenu("mes_conventions");
    };

    const displayProfil_Convocation = () => {
        setmenu("mes_convocations");
    };


    const displayProfil_Attestation = () => {
        setmenu("mes_attestations");
    };


    const displayProfil_Stagiaires = () => {
        setmenu("mes_stagiaires");
    };

    const displayProfil_Tout_Documents = () => {
        setmenu("tout_documents");
    };

    const displayProfil_Modules_Mes_Documents = () => {
        setmenu("modules_mes_documents");
    };

    const upgradetopro = () => {
        setmenu("upgradecompte");
    };

    const displayPersoInfo = () => {
        setmenu("affichage");
    };



    const [connected_user_data, setconnected_user_data] = useState();

    function GetUserNameFromToken(event) {

        var form = new FormData();

        form.append("token", stored_user);

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

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

                setusername(JSON.parse(res.data.message).email);
                if (JSON.parse(res.data.message).migrated &&
                    String(JSON.parse(res.data.message).migrated) === String("1")) {
                    setmigratedaccount(String(JSON.parse(res.data.message).migrated));
                }


                setconnected_user_data(JSON.parse(res.data.message));

                //setmyApiResponse("true");
                //setResult(res.data.message)
                //setmyApimyApiMessage("OK")
            }
            else {
                //console.log(" In GetUserNameFromToken  res.data.status = " + res.data.status);
                //console.log(" In GetUserNameFromToken  res.data.message = " + res.data.message);
                //setmyApiResponse("false");
                //setmyApimyApiMessage("")
            }


        }).catch((error) => {
            console.warn('In GetUserNameFromToken Not good man :( mysearchtext = ', error);
            //setmyApiResponse("false");
            //setmyApimyApiMessage("")
        })
    }



    function finaldeleteuseraccount(e) {

        var form = new FormData();
        form.append("token", stored_user);
        // Ajout des info IP user
        form.append("user_ip", IPv4);
        form.append("user_country_code", country_code);
        form.append("user_country_name", country_name);
        form.append("user_city", city);
        form.append("user_postal", postal);
        form.append("user_latitude", latitude);
        form.append("user_longitude", longitude);
        form.append("user_state", state);


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


        axios.post(myurl, form).then(res => {
            if (String(res.data.status) != String("false")) {
                //console.log(" In test  res.data.status = " + res.data.status);
                //console.log(" In test  res.data.message = " + res.data.message);
                setmyApiResponse("true");
                setResult(res.data.message)
                alert(res.data.message);

            }
            else {
                //console.log(" In test  res.data.status = " + res.data.status);
                //console.log(" In test  res.data.message = " + res.data.message);
                setmyApiResponse("false");
                //setmyApimyApiMessage("")
            }


        }).catch((error) => {
            console.warn('Not good man :( mysearchtext = ');
            setmyApiResponse("false");
            //setmyApimyApiMessage("")
        })


    }


    function deletemyaccount(e) {
        confirmAlert({
            title: 'Suppremier votre compte',
            message: 'Cette action va supprimer toutes vos données, Confirmez-vous la suppression du compte ?',
            buttons: [
                {
                    label: 'Oui',
                    onClick: () => finaldeleteuseraccount()
                },
                {
                    label: 'Non',
                    onClick: () => { return }
                }
            ]
        });
    }

    const [selectedFile, setSelectedFile] = useState();
    const [isSelected, setIsSelected] = useState(false);
    const [isnewimage, setisnewimage] = useState();


    const changeHandler = (event) => {
        let file_size = event.target.files[0].size;

        //or if you like to have name and type
        let file_name = event.target.files[0].name;
        let file_type = event.target.files[0].type;


        //alert("file_size =  "+file_size+" file_type = "+file_type+" a = "+a);
        if (file_size > 100000) {
            alert("L'image doit faire moins de 100 Kilo Octets");
            return;
        }
        setSelectedFile(event.target.files[0]);
        setIsSelected(true);
        setuserimgprofil(URL.createObjectURL(event.target.files[0]));
    };

    function sendImage(e) {
        formData.append('File', selectedFile);
        formData.append("token", stored_user);
        formData.append("type", "user");
        fetch(
            process.env.REACT_APP_API_URL + "myclass/api/recordImage/",
            {
                method: 'POST',
                body: formData,
            }
        ).then((response) => response.json())
            .then((result) => {
                //console.log('Success:', result['message']);
                setIsSelected(false);

            })
            .catch((error) => {
                console.error('Error:');
                setIsSelected(true);
            });
    };

    return (
        <div className="account">
            <Helmet>
                <title>Création compte MySy Trainig Technology</title>
                <meta name="description" content="Éditeur Français de logiciels pour organisme de formation. Avec solutions de E-Learning, gestion administrative et gestion relation client nous accompagnons les organismes de formation à réaliser l’audit QUALIOPI en toute sérénité. Nous sommes les moins cher du marché. Nous vous accompagnons automatiser vos process : inscription, évaluation, émargement (qr-code), Check-list QUALIOPI, Personnalisation et édition documents, Gestion formateurs, Catalogue formations personnalisé" />
                <meta name="robots" content="index,follow" />
                <meta name="title" content="Création compte MySy Trainig Technology" />
                <link rel="canonical" href={window.location.href} />
            </Helmet>

            <h1 style={{ fontSize: '0.1px', opacity: '0' }}>Éditeur Français de logiciels pour organisme de formation. Avec solutions de E-Learning, gestion administrative et gestion relation client nous accompagnons les organismes de formation à réaliser l’audit QUALIOPI en toute sérénité. Nous sommes les moins cher du marché. Nous vous accompagnons automatiser vos process : inscription, évaluation, émargement (qr-code), Check-list QUALIOPI, Personnalisation et édition documents,
                Gestion formateurs, Catalogue formations personnalisé </h1>

      

            <div className="div_mobile">
                <div>
                    <h1 className="h1_transparent">Connexion MySy Training Technology </h1>
                </div>
                <div>
                    <div className="div_gauche">
                        <div>
                            <img class="img-responsive img_user" src={userimgprofil} align="center" alt="MySy Training profile image" />

                            {!isSelected && <div className="nonlable">
                                <input type="file" id="files" accept="image/*" onChange={changeHandler} style={{ opacity: "0", zIndex: "-1", maxWidth: "5px", maxHeight: "0px" }} />
                                <label for="files" className="label">Changer image</label>
                            </div>}

                            {isSelected && <div className="nonlable">
                                <Button variant="outlined" onClick={sendImage} >Enregistrer</Button>
                            </div>}

                        </div>
                        <div className="nom_prenom">     {username && <b> {username} </b>}
                            {!username && <b> xxxx </b>} </div>
                        <hr className="my_hr" />

                        {/** Menu pour un utilisateur de type 'user'. Exemple, l'intranet du client d'un client */}

                        {connected_user_data && connected_user_data.type &&
                            String(connected_user_data.type) === "user" &&
                            <div>
                                {String(menu) !== "affichage" && <div className="sousmenu" onClick={displayPersoInfo}>  INFORMATIONS PERSONNELLES</div>}
                                {String(menu) === "affichage" && <div className="sousmenu sousmenu_selected" onClick={displayPersoInfo}>  INFORMATIONS PERSONNELLES</div>}
                                <hr className="my_hr" />
                                {/*{String(menu) !== "affichage" && <div className="sousmenu" onClick={"displayProfil_Facture"}>  CATALOGUE</div>}
                                {String(menu) === "affichage" && <div className="sousmenu sousmenu_selected" onClick={"displayProfil_Facture"}>  CATALOGUE</div>}
                                <hr className="my_hr" />*/}
                                {String(menu) !== "mes_stagiaires" && <div className="sousmenu" onClick={displayProfil_Stagiaires}>  APPRENANTS</div>}
                                {String(menu) === "mes_stagiaires" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Stagiaires}>  APPRENANTS</div>}
                                <hr className="my_hr" />
                                {String(menu) !== "mes_conventions" && <div className="sousmenu" onClick={displayProfil_Convention}> CONVENTIONS </div>}
                                {String(menu) === "mes_conventions" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Convention}> CONVENTIONS </div>}
                                <hr className="my_hr" />
                                {String(menu) !== "mes_convocations" && <div className="sousmenu" onClick={displayProfil_Convocation}> CONVOCATIONS </div>}
                                {String(menu) === "mes_convocations" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Convocation}> CONVOCATIONS </div>}
                                <hr className="my_hr" />
                                {String(menu) !== "mes_attestations" && <div className="sousmenu" onClick={displayProfil_Attestation}> ATTESTATIONS </div>}
                                {String(menu) === "mes_attestations" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Attestation}> ATTESTATIONS </div>}
                                <hr className="my_hr" />
                                {String(menu) !== "mes_devis" && <div className="sousmenu" onClick={displayProfil_Devis}> DEVIS</div>}
                                {String(menu) === "mes_devis" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Devis}> DEVIS</div>}
                                <hr className="my_hr" />
                                {String(menu) !== "mes_factures" && <div className="sousmenu" onClick={displayProfil_Facture}> FACTURES</div>}
                                {String(menu) === "mes_factures" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Facture}> FACTURES</div>}
                                <hr className="my_hr" />

                                {String(menu) !== "modules_mes_documents" && <div className="sousmenu" onClick={displayProfil_Modules_Mes_Documents}> TOUS LES DOCUMENTS</div>}
                                {String(menu) === "modules_mes_documents" && <div className="sousmenu sousmenu_selected" onClick={displayProfil_Modules_Mes_Documents}> TOUS LES DOCUMENTS</div>}
                                <hr className="my_hr" />
                                {/*<div className="sousmenu" onClick={deletemyaccount}>  SUPPRIMER MON COMPTE</div>
                                <hr className="my_hr" />*/}
                            </div>}

                        {/** Menu pour un utilisateur NON type 'user'  exemple un apprenant */}
                        {connected_user_data && connected_user_data.type &&
                            String(connected_user_data.type) !== "user" &&
                            <div>
                                <div className="sousmenu" onClick={displayPersoInfo}>  INFORMATIONS PERSONNELLES</div>
                                <hr className="my_hr" />
                                <div className="sousmenu" onClick={displayProfil_Objectif}> PROFILS & OBJECTIFS</div>
                                <hr className="my_hr" />
                                <div className="sousmenu" onClick={"displayProfil_Objectif"}> MES DOCUMENTS</div>
                                <hr className="my_hr" />
                                <div className="sousmenu" onClick={displayProfil_Modules_Mes_Documents}> MODULE TOUS DOCUMENTS</div>
                                <hr className="my_hr" />
                                <div className="sousmenu" onClick={displayProfil_Facture}> MES FACTURES</div>
                                <hr className="my_hr" />
                              {/*  <div className="sousmenu" onClick={deletemyaccount}>  SUPPRIMER MON COMPTE</div>
                                <hr className="my_hr" />*/}
                            </div>}

                    </div>
                    <div className="div_droite" style={{ border: 'none' }}>

                        {String(firstConnexion) === "1" &&
                            <div className="div_droite firstConnexion">
                                <div className="firstConnexion_text">
                                    <b>Cher Utilisateur, c'est votre première connexion, </b> <br /> &nbsp;<br />
                                    Nous sommes ravis de vous accueillir. Nous vous invitons à modifier votre mot de passe à partir du menu <i>"MES INFORMATIONS"</i> ==&gt; Pavé <i>"SECURITE"</i> puis <i>"MODIFIER"</i>  <br /><br />
                                    <Button onClick={(e) => setfirstConnexion()} className="firstConnexion_bton"> &nbsp; &nbsp;<FaHandPointRight /> &nbsp; Fermer</Button><br />
                                    &nbsp; <br /> Merci.
                                </div>

                            </div>}

                        {String(myApiResponse) === String("true") && <div className="okUpdateData">
                            {result}

                        </div>}

                        {String(myApiResponse) !== String("true") && <div className="koUpdateData">
                            {result}

                        </div>}
                        {String(menu) === String("affichage") && <UpdateUserInfo />}

                        {String(menu) === String("recherche") && <UserHistoryRecherche />}

                        {String(menu) === String("upgradecompte") && <UpgradeToPro />}

                        {String(menu) === String("profil_objectif") && <Profil_Objectif />}

                        {String(menu) === String("mes_factures") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Intranet_Factures_Client partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={connected_user_data.partner_owner_recid}
                                my_title={"MES DEVIS"}
                                type_document={"devis"}
                                type_user_connected={"user_account"}
                                filter_all_document={"0"}
                            />}

                        {/*String(menu) === String("tout_documents") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Intranet_Tous_Documents partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={connected_user_data.partner_owner_recid}
                            />*/}


                        {String(menu) === String("modules_mes_documents") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Modules_Mes_Documents
                                partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={""}
                                my_title={"Gestion Documentaire"}
                                type_user_connected={"user_account"}
                                type_document={"all"}
                            />}

                        {String(menu) === String("mes_devis") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Modules_Mes_Documents
                                partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={""}
                                my_title={"MES DEVIS"}
                                type_document={"devis"}
                                type_user_connected={"user_account"}
                                filter_all_document={"0"}
                            />}

                        {String(menu) === String("mes_conventions") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Modules_Mes_Documents partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={""}
                                my_title={"MES CONVENTIONS"}
                                type_document={"convention"}
                                type_user_connected={"user_account"}
                                filter_all_document={"0"}
                            />}


                        {String(menu) === String("mes_convocations") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Modules_Mes_Documents partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={""}
                                my_title={"MES CONVOCATIONS"}
                                type_document={"convocation"}
                                type_user_connected={"user_account"}
                                filter_all_document={"0"}
                            />}

                        {String(menu) === String("mes_attestations") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Modules_Mes_Documents partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={""}
                                my_title={"MES ATTESTATIONS"}
                                type_document={"attestation"}
                                type_user_connected={"user_account"}
                                filter_all_document={"0"}
                            />}


                        {String(menu) === String("mes_stagiaires") && connected_user_data && connected_user_data.partner_owner_recid &&
                            connected_user_data.partner_client_id &&
                            <Intranet_Mes_Stagiaires partner_client_id={connected_user_data.partner_client_id}
                                partner_owner_recid={connected_user_data.partner_owner_recid}

                            />}




                        {String(menu) === String("mes_documents") && <Profil_Objectif />}


                    </div>
                </div>
               

            </div>
        </div>
    );
}

export default Account;

