import React, { useState } from 'react';
import './contact_automatic_files.css';
import axios from "axios";
import Module_Alert_Confirmation from "../Module_Alert_Confirmation";

const ContactForm = ({ style = {} }) => {

  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 [mynote, setmynote] = useState(0);
  const [usermessage, setusermessage] = useState("");
  const [object, setobject] = useState("");
  const [result, setResult] = useState("");
  const [myApiResponse, setmyApiResponse] = useState("");

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    subject: '',
    message: '',
    telephone: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prevState => ({
      ...prevState,
      [name]: value
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
   
    var sender_mail = "";
    var sender_tel = "";
    var token = "";



    ////console.log("contacter " + sender_mail + " - " + sender_tel + " - ")

    var mysubject = document.getElementsByName("subject")[0].value;
    var mymessage = document.getElementsByName("message")[0].value;
    var mysender_name = document.getElementsByName("name")[0].value;
    var mysender_email = document.getElementsByName("email")[0].value;
    var sender_tel = document.getElementsByName("telephone")[0].value;


    //alert("contacter "+mysender_email+" - "+mymessage+" - url = "
    //+process.env.REACT_APP_API_URL+" - user_ip ="+IPv4+" - "+latitude);

    if (String(mysubject).length < 5 || String(sender_tel).length > 250) {
      //alert("Le numéro de téléphone est incorrect");
      setdisplay_alert_mysy("1");
      setalert_message("Le sujet doit faire plus de 5 caractères");
      setalert_type("error");
      return;
    }

    if (String(mymessage).length < 10 || String(mymessage).length > 1500) {
      //alert("Le numéro de téléphone est incorrect");
      setdisplay_alert_mysy("1");
      setalert_message("Le mymessage doit faire plus de 10 caractères");
      setalert_type("error");
      return;
    }

    var re = /\S+@\S+\.\S+/;
    if (re.test(mysender_email) == false) {
    //  alert("L'adresse email est incorrecte");
      setdisplay_alert_mysy("1");
        setalert_message("L'adresse email est incorrecte");
        setalert_type("error");
      return;
    }

    if (String(sender_tel).length < 8 || String(sender_tel).length > 15) {
      //alert("Le numéro de téléphone est incorrect");
      setdisplay_alert_mysy("1");
      setalert_message("Le numéro de téléphone est incorrect");
      setalert_type("error");
      return;
    }

  


    var myurl = process.env.REACT_APP_API_URL + "myclass/api/add_user_message/";
    var form = new FormData();
    form.append("type", "email");
    form.append("recever_mail", "contact@mysy-training.com");
    form.append("recever_tel", "+33769203945");
    form.append("sender_mail", mysender_email);
    form.append("sender_tel", sender_tel);
    form.append("object", mysubject);
    form.append("message", mymessage);
    form.append("sender_name", mysender_name);
    form.append("token", "");
    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);

    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("false");
        setdisplay_alert_mysy("1");
        setalert_message(res.data.message);
        setalert_type("error");
      }

      else if (String(res.data.status) === String("true")) {
        //console.log(" In test  res.data.status (true) = " + res.data.status);
        //console.log(" In test  res.data.message = " + res.data.message);
        document.getElementsByName("subject")[0].value = "";
        document.getElementsByName("message")[0].value = "";
        document.getElementsByName("name")[0].value = "";
        document.getElementsByName("email")[0].value = "";
        document.getElementsByName("telephone")[0].value = "";
        setmyApiResponse("true");

        setFormData({
          name: '',
          email: '',
          subject: '',
          message: '',
          telephone: ''
        });

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

      }
      else {
        //console.log(" contact-nous  statut = " + res.data.status);
        //console.log(" contact-nous   res.data.message = " + res.data.message);
        setmyApiResponse("false");
        setdisplay_alert_mysy("1");
        setalert_message(res.data.message);
        setalert_type("error");

      }
    }).catch((error) => {
      console.warn('contact-nous  Not good man :( mysearchtext = ', error);
      setmyApiResponse("false");

      setdisplay_alert_mysy("1");
      setalert_message("Impossible d'enregistrer le message");
      setalert_type("error");

    })



  };

  const formStyles = {
    container: {
      display: 'flex',
      flexDirection: 'column',
      padding: '40px',
      gap: '20px',
      background: '#FFFFFF',
      borderRadius: '8px',
      boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
      maxWidth: '100%',
      ...style
    },
    rowContainer: {
      display: 'flex',
      flexDirection: 'row',
      gap: '24px',
      width: '100%',
      flexWrap: 'wrap'
    },
    inputGroup: {
      display: 'flex',
      flexDirection: 'column',
      gap: '8px',
      flex: 1,
      minWidth: '250px',
      textAlign: 'left',
    },
    label: {
      fontFamily: 'DM Sans',
      fontWeight: 600,
      fontSize: '14px',
      letterSpacing: '0.28px',
      textTransform: 'uppercase',
      lineHeight: '120%',
      color: '#16274F'
    },
    input: {
      padding: '15px 16px',
      background: '#F9FAFB',
      border: '1px solid #CBD5E0',
      borderRadius: '4px',
      fontFamily: 'Inter',
      fontSize: '14px',
      lineHeight: '126%',
      color: '#4B5162',
      width: '100%'
    },
    select: {
      padding: '12px 16px',
      background: '#F9FAFB',
      border: '1px solid #CBD5E0',
      borderRadius: '4px',
      fontFamily: 'Inter',
      fontSize: '14px',
      lineHeight: '126%',
      color: '#4B5162',
      width: '100%'
    },
    textarea: {
      padding: '16px',
      background: '#F9FAFB',
      border: '1px solid #CBD5E0',
      borderRadius: '4px',
      fontFamily: 'Inter',
      fontSize: '14px',
      lineHeight: '126%',
      color: '#4B5162',
      minHeight: '153px',
      resize: 'vertical',
      width: '100%'
    },
    button: {
      padding: '12px 16px',
      background: '#3E6EE3',
      borderRadius: '200px',
      border: 'none',
      color: '#FFFFFF',
      fontFamily: 'DM Sans',
      fontWeight: 700,
      fontSize: '14px',
      lineHeight: '126%',
      cursor: 'pointer',
      width: 'fit-content',
      alignSelf: 'center',
      minWidth: '250px',

    }
  };


  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("");
  }


  return (
    <form onSubmit={handleSubmit} style={formStyles.container}>
      {/***  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*/}

      <div style={formStyles.rowContainer}>
        <div style={formStyles.inputGroup}>
          <label style={formStyles.label}>Nom</label>
          <input
            type="text"
            name="name"
            placeholder="Votre nom"
            value={formData.name}
            onChange={handleChange}
            style={formStyles.input}
          />
        </div>
        <div style={formStyles.inputGroup}>
          <label style={formStyles.label}>E-mail</label>
          <input
            type="email"
            name="email"
            placeholder="Votre e-mail"
            value={formData.email}
            onChange={handleChange}
            style={formStyles.input}
          />
        </div>

        <div style={formStyles.inputGroup}>
          <label style={formStyles.label}>Téléphone</label>
          <input
            type="text"
            name="telephone"
            placeholder="Votre numéro de téléphone"
            value={formData.telephone}
            onChange={handleChange}
            style={formStyles.input}
          />
        </div>
      </div>

      <div style={formStyles.inputGroup}>
        <label style={formStyles.label}>Sujet</label>
        <select
          name="subject"
          value={formData.subject}
          onChange={handleChange}
          style={formStyles.select}
        >
          <option value="">Sélectionner un sujet</option>
          <option value="general">Général</option>
          <option value="support">Support</option>
          <option value="business">Business</option>
        </select>
      </div>

      <div style={formStyles.inputGroup}>
        <label style={formStyles.label}>Votre message</label>
        <textarea
          name="message"
          placeholder="Votre message"
          value={formData.message}
          onChange={handleChange}
          style={formStyles.textarea}
        />
      </div>

      <button type="submit" style={formStyles.button}>
        Envoyer votre message
      </button>
    </form>
  );
};

export default ContactForm;

