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

import { useHistory } from "react-router-dom";

import { useCookies } from "react-cookie";
import { confirmAlert } from 'react-confirm-alert';

import img_met_program from "../mysy_img/met_programmation.jpg";

import img_met_graphisme from "../mysy_img/metier_graphisme.jpg";

import img_met_autre from "../mysy_img/met_autre.jpg";
import img_met_digital from "../mysy_img/met_digital.jpg";
import img_met_management from "../mysy_img/met_management.jpg";

import img_met_dev_perso from "../mysy_img/metier_dev_perso.jpg";
import img_met_rh from "../mysy_img/met_rh.jpg";

import img_met_bureautic from "../mysy_img/met_burautic.jpg";
import img_met_vente from "../mysy_img/met_vente.jpg";
import axios from "axios";
//import { Rating } from 'react-simple-star-rating'
import Rating from '@mui/material/Rating';
import parse from 'html-react-parser'


const Ent_Student_Affichage_Ftion_Grid = (props) => {
  const [userconnected, setuserconnected] = useState("0");
  const [partnerconnected, setpartnerconnected] = useState("0");
  const [cookie, setCookie, removeCookie] = useCookies(['tokenmysych']);
  const [cookie_part, setCookie_part, removeCookie_part] = useCookies(['tokenmysypart']);
  const history = useHistory();
  const [myfilter, setmyfilter] = useState(props.formation.price);

  const [profileimg, setprofileimg] = useState(props.formation.price);


  // Gestion des Cookies
  const stored_partner = cookie_part.tokenmysypart;
  const stored_user = cookie.tokenmysych;

  function test(val) {

    if (userconnected === "0" && partnerconnected === "0") {
      confirmAlert({
        title: 'Activer votre session ?',
        message: 'Merci de vous connecter pour acceder au detail de cette formation',
        buttons: [
          {
            label: 'Oui',
            onClick: () => { history.push("/mysy-training-login/training/" + props.formation.internal_url) }
          },
          {
            label: 'Non',
            onClick: () => { return }

          }
        ],
        closeOnEscape: false,
        closeOnClickOutside: false,
        keyCodeForClose: [8, 32],
        willUnmount: () => { },
        afterClose: () => { },
        onClickOutside: () => { },
        onKeypress: () => { },
        onKeypressEscape: () => { },
      });
    } else {
      window.open(
        "/Display-Detail-formation/" + props.formation.internal_url,
        '_blank'
      );
    }


  }

  const [myclassimage, setmyclassimage] = useState();
  const [isclassimage, setisclassimage] = useState("False");
  const [userimgclassprofil, setuserimgclassprofil] = useState("");

  const [class_img_stored_in_bdd, setclass_img_stored_in_bdd] = useState("");

  function getClassImage_no_token() {

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

    var form = new FormData();

    form.append("type", "partner");
    form.append("related_collection", "myclass");
    form.append("related_collection_recid", props.formation._id);
    form.append("class_external_code", props.formation.external_code);

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

      //   console.log(" getClassImage_no_token : In test  res.data.status = ", res.data.status);
      if (String(res.data.status) === "true") {


        //console.log(" getClassImage_no_token: res.data.message.img = ", res.data.message);

        if (res.data.message.img.length > 0) {
          setisclassimage("True");
        }
        else {
          setisclassimage("False");
        }
        setisclassimage(res.data.message.img);
        var ch_img = "data:image/png;base64," + res.data.message.img;
        setclass_img_stored_in_bdd(ch_img);
        // console.log(" getClassImage_no_token: setclass_img_stored_in_bdd = ", setclass_img_stored_in_bdd);

      }
      else {
        // console.log(" In Erreur   res.data.status = " + res.data.status);
        //console.log(" In Erreur  res.data.message = " + res.data.message);
        setisclassimage("False");
        setuserimgclassprofil();
        setclass_img_stored_in_bdd();
      }
    }).catch((error) => {

      console.warn('getClassImage ee: Not good man :( getClassImage = ');
      setisclassimage("False");
      setuserimgclassprofil("");
      setclass_img_stored_in_bdd("");
    })

  }


  /* Cette variable accompagne la gestion des images par defaut.
  idée : si la valeur de "DetailTraining.metier" != "management, digital, office, rh, vente, dev_perso"
  alors l'utilisateur à créer une formation avec un metier qui n'est pas geré, donc on met une image par defaut
  */
  const [ismetiermanaged, setismetiermanaged] = useState();
  const liste_metier = ["management", "digital", "office", "rh", "vente", "dev_perso"];

  useEffect(() => {
    setmyfilter(props.myfil);

    // console.log(" #### useEffect props.formation = ", props.formation);


    if (typeof (stored_user) === "undefined" || String(stored_user) === '') {
      setuserconnected("0");
    } else {
      setuserconnected("1");
    }

    if (typeof (stored_partner) === "undefined" || String(stored_partner) === '') {
      setpartnerconnected("0");
    } else {
      setpartnerconnected("1");
    }

    getClassImage_no_token();
    GetCurrentClass_trainingsession();

    GetCurrentClass_trainingsession_cities();

    // Verifier si le metier est geré
    if (props.formation.metier) {
      if (!liste_metier.includes(props.formation.metier)) {
        setismetiermanaged("0"); // j'ai une valeur dans metier, mais qui n'est pas geré
      }
    }
    else {
      setismetiermanaged("0");
    }

    if (props.formation.img_url && String(props.formation.img_url).length > 0) {
      setismetiermanaged("1");
    }

  }, []);


  const [GetCurrentClass_api, setGetCurrentClass_api] = useState();
  const [GetCurrentClass_message, setGetCurrentClass_message] = useState();
  const [GetCurrentClass_result, setGetCurrentClass_result] = useState();
  function GetCurrentClass_trainingsession(event) {

    var form = new FormData();

    form.append("class_internal_url", props.formation.internal_url);

    form.append("token", stored_partner);

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

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

      if (res.data.status != "false") {
        //console.log(" In GetCurrentClass_trainingsession  res.data.status = " + res.data.status);
        //console.log(" In GetCurrentClass_trainingsession  res.data.message r_class = " + res.data.message);
        setGetCurrentClass_api("true");
        setGetCurrentClass_result(res.data.message);
      }
      else {
        setGetCurrentClass_api("false");
        setGetCurrentClass_message(res.data.message);
      }

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


  const [GetCurrentClass_trainingsession_cities_api, setGetCurrentClass_trainingsession_cities_api] = useState();
  const [GetCurrentClass_trainingsession_cities_message, setGetCurrentClass_trainingsession_cities_message] = useState();
  const [GetCurrentClass_trainingsession_cities_result, setGetCurrentClass_trainingsession_cities_result] = useState([]);
  function GetCurrentClass_trainingsession_cities(event) {

    var form = new FormData();

    form.append("class_internal_url", props.formation.internal_url);

    form.append("token", stored_partner);

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

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

      if (res.data.status != "false") {
        //console.log(" In GetCurrentClass_trainingsession_cities  res.data.status = " + res.data.status);
        //console.log(" In GetCurrentClass_trainingsession_cities  res.data.message r_class = " + res.data.message);
        setGetCurrentClass_trainingsession_cities_api("true");
        setGetCurrentClass_trainingsession_cities_result(res.data.message);
      }
      else {
        setGetCurrentClass_trainingsession_cities_api("false");
        setGetCurrentClass_trainingsession_cities_message(res.data.message);
      }

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

  const styles = {
    list: {
      display: 'flex',
      flexDirection: 'column',
      gap: '32px',
      width: '100%',
    },
    row: {
      display: 'flex',
      flexDirection: 'row',
      gap: '24px',
      width: '100%',
    },
    card: {
      flexGrow: 1,
      backgroundColor: '#fff',
      borderRadius: '8px',
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column',
    },
    image: {
      maxWidth: '100%',
      height: '200px',
      overflow: 'hidden',
      marginTop: '-2rem'

    },
    content: {
      padding: '16px',
    },
    header: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    eligibility: {
      backgroundColor: '#e2e9fb',
      padding: '4px 8px',
      borderRadius: '4px',
      fontSize: '12px',
      fontWeight: 'bold',
    },
    title: {
      fontSize: '14px',
      fontWeight: 'bold',
      margin: '8px 0',
    },
    price: {
      fontSize: '14px',
      fontWeight: 'bold',
      color: '#000',
    },
    description: {
      fontSize: '12px',
      color: '#666',
      margin: '8px 0',
      height: "40px",
      overflow: "hidden",
    },
    details: {
      display: 'flex',
      justifyContent: 'space-between',
      marginTop: '16px',
    },
    button: {
      backgroundColor: '#007bff',
      color: '#fff',
      padding: '8px 16px',
      border: 'none',
      borderRadius: '4px',
      cursor: 'pointer',
    },
    buttonOutline: {
      backgroundColor: '#fff',
      color: '#007bff',
      padding: '8px 16px',
      border: '1px solid #007bff',
      borderRadius: '4px',
      cursor: 'pointer',
    },
  };

  return (

    <div className="new_formation_2025">


      <div style={styles.card}>
        <div style={{ width: '100%', textAlign: 'right', zIndex: '9999' }}>

          <div style={{ width: '50%', float: 'left' }}> &nbsp; </div>

          {props.formation.cpf && String(props.formation.cpf) === String("1") && <div className="case_cpf" >
            <span className="tag_cpf_txt_ok_cpf" >{"OUI CPF"}</span>
          </div>
          }
          {props.formation.cpf && String(props.formation.cpf) !== String("1") && <div className="case_cpf">
            <span className="tag_cpf_txt_no_ok_cpf">{"NON CPF"}</span>
          </div>
          }
          {!props.formation.cpf && String(props.formation.cpf) !== String("1") && <div className="case_cpf">
            <span className="tag_cpf_txt_no_ok_cpf">{"NON CPF"}</span>
          </div>}

        </div>


        {class_img_stored_in_bdd && String(class_img_stored_in_bdd).length > 50 &&
          <img src={class_img_stored_in_bdd} alt="Formation" style={styles.image} />
        }

        {(!class_img_stored_in_bdd || String(class_img_stored_in_bdd).length < 50) &&
          (!props.formation.img_url || String(props.formation.img_url).length <= 10) &&
          String(ismetiermanaged) !== "0" && String(ismetiermanaged) !== "1" &&

          <div >

            {(!props.formation.img_url || String(props.formation.img_url).length <= 0) &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("it") &&
              String(isclassimage) === "False" && <img src={img_met_program} alt="informatique" style={styles.image} />}

            {(!props.formation.img_url || String(props.formation.img_url).length <= 0) &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("graphisme") &&
              String(isclassimage) === "False" && <img src={img_met_graphisme} alt="graphisme" style={styles.image} />}

            {(!props.formation.img_url || String(props.formation.img_url).length <= 0) &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("management") &&
              String(isclassimage) === "False" && <img src={img_met_management} alt="management" style={styles.image} />}

            {(!props.formation.img_url || String(props.formation.img_url).length <= 0) &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("digital") &&
              String(isclassimage) === "False" && <img src={img_met_digital} alt="digital" style={styles.image} />}

            {(!props.formation.img_url || String(props.formation.img_url).length <= 0) &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("office") &&
              String(isclassimage) === "False" && <img src={img_met_bureautic} alt="office" style={styles.image} />}

            {!props.formation.img_url || String(props.formation.img_url).length <= 0 &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("rh") &&
              String(isclassimage) === "False" && <img src={img_met_rh} alt="ressources humaines" style={styles.image} />}

            {!props.formation.img_url || String(props.formation.img_url).length <= 0 &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("vente") &&
              String(isclassimage) === "False" && <img src={img_met_vente} alt="vente" style={styles.image} />}

            {!props.formation.img_url || String(props.formation.img_url).length <= 0 &&
              props.formation.metier && String(props.formation.metier).toLocaleLowerCase() === String("dev_perso") &&
              String(isclassimage) === "False" && <img src={img_met_dev_perso} alt="developpement personnel" style={styles.image} />}

            {String(isclassimage) === "True" && <img src={userimgclassprofil} alt="developpement personnel" style={styles.image} />}


          </div>
        }

        {(!class_img_stored_in_bdd || String(class_img_stored_in_bdd).length < 50) && String(ismetiermanaged) === "0" && String(userimgclassprofil).length > 100 &&
          <div>
            <img src={userimgclassprofil} alt="autre" style={styles.image} />
            {/*props.formation.institut_formation && <div style={{ width: '100%', "textAlign": "center" }}> Dispensé par :<br /> 
          {String(props.formation.institut_formation)}  </div>*/}
          </div>}

        {(!class_img_stored_in_bdd || String(class_img_stored_in_bdd).length < 50) && String(ismetiermanaged) === "0" && String(userimgclassprofil).length <= 100 &&
          <div>
            <img src={img_met_autre} alt="autre" style={styles.image} />
            {/*props.formation.institut_formation && <div style={{ width: '100%', "textAlign": "center" }}> Dispensé par :<br /> 
          {String(props.formation.institut_formation)}  </div>*/}
          </div>}

        {(!class_img_stored_in_bdd || String(class_img_stored_in_bdd).length < 50) && String(ismetiermanaged) === "1" &&
          <div>
            <img src={props.formation.img_url} alt="autre" style={styles.image} />
            {/*props.formation.institut_formation && <div style={{ width: '100%', "textAlign": "center" }}> Dispensé par : <br /> 
          {String(props.formation.institut_formation)} </div>*/}
          </div>}


        <div className="block_main_contente">
          <div className="block_top_content">
            <div className="div_row_gauche" >
              {props.formation.note && String(props.formation.note).length === 1 &&
                parseInt(String(props.formation.note)) <= 5 &&
                <Rating name="half-rating-read" defaultValue={props.formation.note} precision={0.5} readOnly style={{ fontSize: '15px' }} />
              }
            </div>

            <h3 className="formation_titre">{String(parse(String(props.formation.title).replace(/(<([^>]+)>)/ig, ''))).substring(0, 50)}</h3>
            {props.formation.discounted_price && props.formation.business_prices && <p className="formation_prix">{props.formation.discounted_price}  € HT&nbsp; </p>}

            {props.formation.business_prices && props.formation.business_prices.length <= 0
              && <p className="formation_prix">{props.formation.price}  € HT&nbsp; </p>}

            {props.formation.business_prices && props.formation.business_prices.length > 0 &&
              <p style={{ width: '100%', float: 'left' }}>

                <p className="formation_prix" style={{ width: '100%', float: 'left' }}>{props.formation.business_prices[0].discounted_price}€ HT&nbsp;
                  <font className='training_price_barre' style={{ fontSize:'14px' }}> {props.formation.price} € HT &nbsp;</font>
                  <font className='discount_block' style={{ fontSize:'14px' }}> ({props.formation.business_prices[0].discount} %) </font></p>
              </p>}

            <p className="formation_description"> {String(parse(String(props.formation.description).replace(/(<([^>]+)>)/ig, ''))).substring(0, 80)}...</p>
          </div>

        </div>
        <div className="block_cats">
          <button className="block_cats_bton_detail">
            <nav className="block_cats_bton_detail_text"
              onClick={(e) => {
                e.preventDefault();
                if (props.formation.url && props.formation.url.length > 5) {

                  window.open(
                    props.formation.url,
                    '_blank'
                  );
                } else {
                  window.open(
                    "/detaile-formation/" + props.formation.internal_url,
                    '_blank'
                  );
                }
              }}> Voir les détails </nav></button>

        </div>
      </div>
   
    </div>

  )
}


export default Ent_Student_Affichage_Ftion_Grid;