import React, { useRef, useState, useEffect } from "react";
import axios from "axios";
import { useParams } from 'react-router-dom'
import { Helmet } from "react-helmet";
import { useCookies } from "react-cookie";
import Articles from "../components/Article";
import 'react-discussion-board/dist/index.css'
import { useForm } from 'react-hook-form';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import parse from 'html-react-parser'
import Fotter_v3 from "./Fotter_v3";
import Header from "./Header";
import img_met_digital from "../mysy_img/met_digital.jpg";


const DisplayDetailArticle_new_v2 = (props) => {
  const [cookie, setCookie, removeCookie] = useCookies(['tokenmysych']);
  const { articleId } = useParams();
  const [result, setResult] = useState("");

  const [myApiResponse, setmyApiResponse] = useState("false");
  const [DetailArticleAvis, setDetailArticleAvis] = useState([]);
  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 [userIp, setuserIp] = useState("");
  const [action, setaction] = useState("");
  const [userconnected, setuserconnected] = useState("");
  const stored_user = cookie.tokenmysych;

  const [display_header_img, setdisplay_header_img] = useState("");

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors }
  } = useForm();


  const [pagecanoniktitle, setpagecanoniktitle] = useState("");
  const [pagecanonikurl, setpagecanonikurl] = useState(window.location.host);
  const [article_img, setarticle_img] = useState("")
  const [page_meta_description, setpage_meta_description] = useState("");


  useEffect(() => {

    setpagecanonikurl(window.location.host);

    async function fetchData() {
      const result = await axios('https://geolocation-db.com/json/',);
      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);

    }
    fetchData();
    Display();
    //  Display_article_comment();
    Get_3_Articles();

    //alert("stored_user =  "+stored_user);
    if (typeof (articleId) === "undefined") {
      setaction("creation");
    } else {
      setaction("affichage");

    }

    if (typeof (stored_user) === "undefined" || String(stored_user) === '') {
      setuserconnected("0");
    } else {
      setuserconnected("1");
    }
    //setwindowWidth(window.innerWidth);
   // setwindowheight(window.innerHeight);


    //console.log(" articleId = " + articleId);
  }, []);


  function Display(e) {


    var myurl = process.env.REACT_APP_API_URL + "myclass/api/get_articles_avis/";
    var form = new FormData();
    form.append("internal_url", articleId);
    form.append("token", "");
    // 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);


    //alert("myurl = "+myurl);

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

        setResult(res.data.message);
        setDetailArticleAvis(JSON.parse(res.data.message));

        var my_avis = JSON.parse(res.data.message)

        if (my_avis && my_avis.display_header_img && String(my_avis.display_header_img) === "0") {
          setdisplay_header_img("0")
        }

        if (my_avis && my_avis.title_formation) {
          setpagecanoniktitle(my_avis.title_formation);
        }

        if (my_avis && my_avis.meta_description) {
          setpage_meta_description(my_avis.meta_description);
        } else {
          setpage_meta_description(my_avis.title_formation);
        }


        if (my_avis && my_avis.internal_url) {
          setpagecanonikurl(my_avis.internal_url);

          console.log(process.env.REACT_APP_BASE_URL + "/" + my_avis.internal_url);
        }


        if (my_avis && my_avis.img_path && String(my_avis.img_path).length > 10) {
          setarticle_img(my_avis.img_path);
        } else {
          setarticle_img(img_met_digital);
        }

        //  console.log(" ### my_avis.display_header_img = ", my_avis.display_header_img);
      }
      else {
        //console.log(" In Erreur   res.data.status = " + res.data.status);
        //console.log(" In Erreur  res.data.message = " + res.data.message);
        setmyApiResponse("False");
      }
    }).catch((error) => {
      console.warn('Not good man :( mysearchtext = ');
      setmyApiResponse("False");
    })
  }

  const [Get_3_Articles_api, setGet_3_Articles_api] = useState();
  const [Get_3_Articles_result, setGet_3_Articles_result] = useState([]);
  function Get_3_Articles(e) {
    var myurl = process.env.REACT_APP_API_URL + "myclass/api/get_last_3_articles/";
    var form = new FormData();
    form.append("internal_url", articleId);
    form.append("token", "");
    // 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);


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

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

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

        setGet_3_Articles_result(res.data.message);

      }
      else {
        //console.log(" In Erreur   res.data.status = " + res.data.status);
        //console.log(" In Erreur  res.data.message = " + res.data.message);
        setGet_3_Articles_result([]);
        setGet_3_Articles_api("False");

      }
    }).catch((error) => {
      console.warn('Not good man :( mysearchtext = ');
      setGet_3_Articles_api("False");
    })
  }

  return (
    <div style={{ width: "100%", float: "left" }}>
      <div className="DisplayDetailArticle">


        <Helmet>
          <title>{`${pagecanoniktitle}`}</title>
          <meta name="title" content={`${pagecanoniktitle}`} />
          <meta name="description" content={`${page_meta_description}`} />
          <meta name="robots" content="index,follow" />
          <link rel="canonical" href={window.location.href} />
       
        </Helmet>


        <Header />

        <div className="div_mobile">

          <div className="div_row style_perso" >
            <div className="Background-header">

              <div className="Title">

                {DetailArticleAvis && DetailArticleAvis.title_formation &&
                  <div className="besoin_aide">
                    <h1 className="title_h1">  {DetailArticleAvis.title_formation} </h1>
                    {DetailArticleAvis && DetailArticleAvis.date_avis && <div className="detail_text_aide">
                      {(String(DetailArticleAvis.date_avis)).substring(0, 16)}
                    </div>}
                  </div>}

              </div>


            </div>



          </div>
          <div style={{ width: '100%' }}>
            <div className="block_centrer">


              <div className="aricles_a_la_une">

                {DetailArticleAvis && DetailArticleAvis.avis && <div className="desc_article">
                  {
                    <div>

                      {/*** important :  si DetailArticleAvis.avis === "0", alors on 
                     * n'affiche pas l'image d'entete.
                     * Cela permet de gerer les articles sans image
                     * 
                     */}

                      {String(display_header_img) !== "0" && <div style={{ "width": "100%", "height": "15rem", textAlign: "center" }}>
                        <img src={article_img} alt={pagecanoniktitle} className="img_photo" id="projets" />
                      </div>}

                      <div className="avis">


                        {<div style={{ "marginTop": "1rem" }}>

                          {parse(DetailArticleAvis.avis)}


                        </div>}
                      </div>

                    </div>
                  }
                </div>}


              </div>

            </div>
          </div>


          <div className="block_centrer">
            <div className="retour_list_articles" onClick={(e) => {

              e.preventDefault();
              window.location.href = "/Recherche-Article-formation"
            }}>
              Retour vers la liste des articles
            </div>
          </div>

          <div style={{ width: '100%' }}>

            <div className="liste_articles">
              <div className="titre_possible_interet" > Cela pourrait aussi vous intéresser</div>
              {Get_3_Articles_result && Get_3_Articles_result.map((formation) => (
                <div className="block_article" >
                  <Articles article={JSON.parse(formation)} key={JSON.parse(formation).title_formation} />
                </div>

              ))}



            </div>
          </div>

        </div>

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

      </div>
      <div style={{ height: "5rem", width: "100%" }}>
        <Fotter_v3 />
      </div>

    </div>

  )
}

export default DisplayDetailArticle_new_v2;