import React, { useState, useEffect } from "react";
import axios from "axios";
import partnerbannerimg from "../mysy_img/MYSY_banner_compte.png";
import profileimg from "../mysy_img/MYSY-profil-2.png";
import TrainingForm from "./AddClassManual"
import PartnerTranings from "./DisplayPartnerTrainingsPagination";
import HebergementLms from "./HebergementLms";
import Button from '@mui/material/Button';
import SendIcon from '@mui/icons-material/Send';
import { getCookie } from 'react-use-cookie';
import { useHistory } from "react-router-dom";
import PartnerInfo from "./UpdatePartnerInfo";
import PartenairStat from "./PartenairStat";
import { Helmet } from "react-helmet";
import bannerimg2 from "../mysy_img/MYSY-LOGO-BLUE.png";
import logowhite from "../mysy_img/MYSY-LOGO-WHITE.png";

import downarrow from "../mysy_img/downarrow.png";
import uparrow from "../mysy_img/uparrow.png";
import excel_icone from "../mysy_img/excel_icone.png";
import participants from "../mysy_img/participants.png";
import Box from '@mui/material/Box';
import Footer from "./Fotter";
import { confirmAlert } from 'react-confirm-alert'; // Import
import { useCookies } from "react-cookie";
import Header from "./Header";
import Facture from "./Facture";
import Abonnement from "./Abonnement";
import { useLocation } from "react-router-dom";
import { useParams } from 'react-router-dom'
import CheckOut from "./CheckOut";
import { IoCheckmarkCircleSharp } from "react-icons/io5";
import { FaHandPointRight } from "react-icons/fa";
import OrderConfirmation from "./OrderConfirmation";
import Pricing from "./Pricing";
import {
    FcHome, FcButtingIn, FcDepartment, FcBullish, FcAddDatabase, FcFolder,
    FcList, FcGraduationCap, FcMultipleDevices, FcCurrencyExchange,
    FcMoneyTransfer, FcFeedback, FcKey, FcVideoCall, FcSettings
} from "react-icons/fc";
import { DataGrid, GridToolbar, frFR, GridCellParams } from '@mui/x-data-grid';
import { FcCancel, FcApproval, FcAcceptDatabase, FcPrint, FcDeleteDatabase } from "react-icons/fc";
import { darken, lighten, styled } from '@mui/material/styles';

import AddParnerClient from "./AddPartnerClient";
//import { FcHome} from "react-icons/fc";
import { alpha } from '@mui/material/styles';
import { gridClasses } from '@mui/x-data-grid';
import { AiOutlineUserAdd } from "react-icons/ai";




const Partner_Client = (props) => {

    const history = useHistory();

    const [rows_list_clients, setrows_list_clients] = useState([]);
    const [selectionModel, setSelectionModel] = React.useState([]);
    const columns_clients = [
        { field: 'id', headerName: 'id', hide: true },
        { field: 'email', headerName: 'email', width: 100, hideable: false, flex: 1 },
        { field: 'nom', headerName: 'nom', width: 100, hide: false, editable: true, flex: 1 },


        /*{
            field: "update", headerName: 'Modifier',
            renderCell: (cellValues) => {
                return (

                    <div style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }} onClick={(event) => {
                        handleClick_modifier(event, cellValues);
                    }}>
                        <FcAcceptDatabase style={{ "fontSize": "x-large" }} />
                    </div>

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

                    <div style={{ "marginLeft": "auto", "marginRight": "auto", "cursor": "pointer" }} onClick={(event) => {
                        handleClick_supprimer(event, cellValues);
                    }}>
                        <FcDeleteDatabase style={{ "fontSize": "x-large" }} />
                    </div>

                );
            }
        },


    ]

    const [rowSelectionModel, setRowSelectionModel] = React.useState([]);


    const [Edite_Client, setEdite_Client] = useState("");
    const [Client_email, setClient_email] = useState("");
    function handleClick_modifier(event, cellValues) {
        var clientmail = String(cellValues.row.email);
        setClient_email(clientmail);
        setEdite_Client("1");
    }

    function handleClick_add_new_client(event, cellValues) {
        setEdite_Client("2");
    }


    function handleClick_supprimer(event, cellValues) {
        var clientmail = String(cellValues.row.email);
        alert(" en cours de dev");
    }


    const [Get_List_Partner_Clients_api, setGet_List_Partner_Clients_api] = useState();
    const [Get_List_Partner_Clients_message, setGet_List_Partner_Clients_message] = useState();
    const [Get_List_Partner_Clients_result, setGet_List_Partner_Clients_result] = useState();
    function Get_List_Partner_Clients(event) {

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

        form.append("token", stored_cookie);


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

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

            if (String(res.data.status) === String("true")) {
                setGet_List_Partner_Clients_api("true");
                setGet_List_Partner_Clients_result(res.data.message);
                setrows_list_clients(res.data.message);
            }
            else if (String(res.data.status) === String("Err_Connexion")) {
                alert('Erreur: ' + res.data.message);
                history.push("/Connexion");
            }
            else {
                setGet_List_Partner_Clients_api("false");
                setGet_List_Partner_Clients_message(res.data.message);
            }

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



    function close_detail_client() {

        setEdite_Client("0");

    }


    useEffect(() => {
        //menu_info();
        Get_List_Partner_Clients();

    }, []);



    const [part_client_file_name, setpart_client_file_name] = useState();
    function submenu_import_part_client_mass() {
        setpart_client_file_name();
        setliste_part_client_file_change_api();
        hiddenFileInput.current.click();
    }

    const hiddenFileInput = React.useRef(null);

    const [liste_part_client_file_change_api, setliste_part_client_file_change_api] = useState();
    const [liste_part_client_file_change_result, setliste_part_client_file_change_result] = useState();
    const [liste_part_client_file_change_message, setliste_part_client_file_change_message] = useState();
    const liste_part_client_file_change = event => {
        const fileUploaded = event.target.files[0];
        let file_size = event.target.files[0].size;
        let file_type = event.target.files[0].type;

        //console.log("file_size =  ",file_size," file_type = ",file_type);
        if (file_size > 1000000) {
            alert("Le fichier ne doit pas depasser un 1 Méga octets");
            return;
        }

        setpart_client_file_name(event.target.files[0].name);

        const formData = new FormData();
        formData.append('File', fileUploaded);
        //formData.append('token', 'K3cw63eKokKSbV4spjQ48SUNnfy80yrXfA');
        const stored_cookie = getCookie('tokenmysypart');

        formData.append("token", stored_cookie);

        //console.log("token = " + stored_cookie);

        fetch(
            process.env.REACT_APP_API_URL + "myclass/api/Add_Partner_Client_mass/",
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                if (String(result['status']) === String("true")) {
                    //console.log('Success:', result['message']);
                    setliste_part_client_file_change_result(result['message']);
                    setliste_part_client_file_change_api("true");

                    alert(result['message']);
                    Get_List_Partner_Clients();


                } else if (String(result['status']) === String("Err_Connexion")) {
                    alert('Erreur: ' + result['message']);
                    history.push("/Connexion");
                }

                else {
                    setliste_part_client_file_change_message(result['message']);
                    setliste_part_client_file_change_api("false");
                    alert(result['message']);
                }

            })
            .catch((error) => {
                console.error('Error:', error);
                setliste_part_client_file_change_api("false");
            });

    };

    const datagridSx = {
        borderRadius: 2,
        marginRight: 1,
        marginLeft: 1,
        border: 0,
        "& .MuiDataGrid-main": { borderRadius: 0 },
        /*'& div[data-rowIndex][role="row"]:nth-of-type(5n-4)': {
          color: "blue",
          fontSize: 18,
          //risky
          minHeight: "60px !important",
          height: 60,
          "& div": {
            minHeight: "60px !important",
            height: 60,
            lineHeight: "59px !important"
          }
        },*/
        "& .MuiDataGrid-virtualScrollerRenderZone": {
            "& .MuiDataGrid-row": {
                "&:nth-child(2n)": { backgroundColor: "rgba(235, 235, 235, .7)" }
            }
        },
        "& .MuiDataGrid-columnHeaders": {
            backgroundColor: "#c8cfd5",
            color: "black",
            fontSize: 16
        }
    };


    function handleClick_edit_session_From_Line(selected_row_id) {
        if (rows_list_clients[selected_row_id]) {
            var line = JSON.parse(rows_list_clients[selected_row_id]);
            var clientmail = String(line.email);
            setClient_email(clientmail);
            setEdite_Client("1");
        }
    }


    return (

        <div className="partner_client">

            <div className="div_row">

                {String(Edite_Client) === "1" && <div className="div_row">

                    <div className="titre1"> Detail client : {Client_email}</div>

                    <AddParnerClient client_mail={Client_email} close_detail_client={close_detail_client} />

                </div>}

                {String(Edite_Client) === "2" && <div className="div_row">

                    <div className="titre1"> Detail client : {Client_email}</div>

                    <AddParnerClient client_mail={Client_email} close_detail_client={close_detail_client} new_customer="1"
                        Get_List_Partner_Clients={Get_List_Partner_Clients} />

                </div>}


                <div className="titre1"> Liste des clients</div>

                <div className="div_row">
                    <div style={{ height: "500px", width: '100%' }}>
                        <div className="div_row">

                            <Button variant="outlined" onClick={submenu_import_part_client_mass} className="detail_class_submenu bton_add_menuclient" style={{
                                "background": "#c8cfd5",
                                "color": "black", "width": "auto"
                            }}
                                id='menu_import_participant' name='menu_import_participant'>Choisir un fichier et Importer &nbsp;
                                <img src={excel_icone} alt="ajout csv" className="icon_excel" />
                            </Button>

                            <Button variant="outlined" onClick={handleClick_add_new_client}
                                className="detail_class_submenu bton_add_menuclient"
                                id='menu_one_participant' name='menu_one_participant'><img src={participants} alt="ajout un client" className="icon_plus" /> &nbsp;
                                Ajouter 1 Client

                            </Button>

                            <br />
                            <a href='/sample/template_import_client.csv' download>Télécharger un fichier modèle</a>
                            <br />

                            <i>{part_client_file_name}</i><br />
                            {String(liste_part_client_file_change_api) === String("true") && <nav className="okUpdateData"> Les client ont été correctement importés</nav>}
                            {String(liste_part_client_file_change_api) === String("false") && <nav className="koUpdateData"> {liste_part_client_file_change_message} </nav>}

                            <input type="file"
                                accept=".csv"
                                ref={hiddenFileInput}
                                style={{ display: 'none' }}
                                name="liste_participants_file"
                                onChange={liste_part_client_file_change}
                            />

                        </div>
                        &nbsp;
                        <Box
                            sx={{
                                height: "500px",
                                width: '100%',
                                paddingRight: '1px',
                                '& .cell--presentiel': {
                                    backgroundColor: '#a2cf6e',
                                    color: '#1a3e72',
                                    fontWeight: 'bold',
                                },



                            }}
                        >
                            <DataGrid
                                localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                                rows={rows_list_clients.map((item, index) => (
                                    {
                                        id: index,
                                        email: JSON.parse(item).email,
                                        nom: JSON.parse(item).nom,

                                    }
                                ))}

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

                                rowsPerPageOptions={[10]}
                                //disableSelectionOnClick
                                checkboxSelection
                                components={{
                                    Toolbar: GridToolbar,
                                }}
                                sx={datagridSx}
                                onSelectionModelChange={(newSelectionModel) => {

                                    setSelectionModel(newSelectionModel);
                                    if (newSelectionModel.length === 1)
                                        handleClick_edit_session_From_Line(newSelectionModel);
                                }}
                                selectionModel={selectionModel}

                            />
                        </Box>
                        <br />


                        <br />
                        {/* <Button variant="contained" onClick={GetAllClass_new}>Contained</Button>*/}
                    </div>
                </div>


                {/*<div className="titre1"> Grid des clients</div>
                <div className="div_row" style={{ "marginLeft": "5px", "marginRight": "5px" }}>
                    <div className="client_grid">

                        {Get_List_Partner_Clients_result && String(Get_List_Partner_Clients_api) === "true" &&
                            Get_List_Partner_Clients_result.map((client) => (

                                <div>
                                    mail = {String(JSON.parse(client).email)} <br />
                                    nom = {String(JSON.parse(client).nom)} <br />
                                    Tel = {String(JSON.parse(client).telephone)} <br />
                                    Adresse = {String(JSON.parse(client).adr_adresse)} - {String(JSON.parse(client).adr_ville)}  <br />

                                </div>


                            ))}
                    </div>
                </div>
                            */}

            </div>


        </div>
    )
}


export default Partner_Client;