import React, { useState, FC } from 'react';
import { validationWithMessages } from '@/utils/validate';
import axios from 'axios';
import * as Yup from 'yup';
import { apiContactMessages, apiToken } from '@/data/constants';

// Librería para el selector de Lada con banderas
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';

// --- FUNCIÓN PARA EL ENVÍO A GOOGLE SHEETS ---
const enviarGoogleSheets = async (datos: any) => {
  const GOOGLE_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbxp9t7DX10i6au0GHSspB6jH1gBJcd36n1zBsOFuvDgNJ00AgnZwmDohRokrkGH_sJh/exec"; 
  try {
    await fetch(GOOGLE_SCRIPT_URL, {
      method: "POST",
      mode: "no-cors", // <--- ESTO EVITA EL ERROR 403/CORS
      headers: {
        "Content-Type": "text/plain", // Cambiar a text/plain ayuda a evitar el pre-flight de CORS
      },
      body: JSON.stringify(datos)
    });
  } catch (error) {
    console.error("Error Sheets:", error);
  }
};

// --- FUNCIÓN PARA EL ENVÍO DE CORREO API ---
const enviarCorreoAPI = async (datos: any, proyectoNombre: string, fechaEnvio: string) => {
    const emailHTML = `
    <center>
      <table bgcolor="#ffffff" cellspacing="0" style="width: 75%;border-spacing:0;border:1px solid #e2e2e2;font-family:'Helvetica',sans-serif">
        <tbody>
          <tr>
            <td colspan="2" bgcolor="#333" style="padding:15px;">
              <h2 style="color:#fff;margin:0;">Información del Proyecto</h2>
            </td>
          </tr>
          <tr>
            <td colspan="2" align="left" style="padding:30px;color:#333;">
              <h3>Información del prospecto</h3>
              Nombre: <strong>${datos.name}</strong><br>
              Email: <strong>${datos.email}</strong><br>
              Teléfono: <strong>${datos.phone}</strong><br>
              Horario preferido: <strong>${datos.schedule}</strong><br>
              Mensaje: <strong>${datos.message || 'N/A'}</strong><br>
              Proyecto: <strong>${proyectoNombre}</strong><br>
              Fecha de envío: <strong>${fechaEnvio}</strong><br>
              <br>
              <p style="font-size:12px; color:#666;">Fuente: ${window.location.href}</p>
            </td>
          </tr>
        </tbody>
      </table>
    </center>`;

    const payload = {
        toName: "GrupoVelasCorporativo",
        emailSubject: `Formulario de Proyectos - Grupo Velas Corporativo`,
        emailPreheader: `Nuevo registro de ${datos.name}`,
        emailHTML: emailHTML,
        toEmail: "dsuarez@velasresorts.com, registros@velasresorts.com"
    };

    try {
        await fetch("https://restapi.velasresorts.com/sendforms", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload)
        });
    } catch (error) {
        console.error("Error al enviar el correo:", error);
    }
};

interface ContactFormProps {
  trans: any;
  cities: any[];
  background?: string;
}

const INITIAL_VALUES = {
  email: '',
  name: '',
  phone: '', // Aquí se guardará el número completo con lada
  schedule: '',
  message: "",
};

const INITIAL_ERRORS = {
  email: '',
  name: '',
  phone: '',
  schedule: '',
  message: "",
  general: ''
};

const ContactForm: FC<ContactFormProps> = ({ trans, cities, background }) => {
  const schedules = trans('projects:quote.schedules', { returnObjects: true });
  const [errors, setErrors] = useState(INITIAL_ERRORS);
  const [formData, setFormData] = useState(INITIAL_VALUES);
  const [status, setStatus] = useState('loaded');

  const handleErrors = (name: string, value: any) => {
    setErrors((prevState) => ({ ...prevState, [name]: value }));
  };

  const yupObjectShape = {
    name: Yup.string().required(trans('common:formMessages.errorRequired')),
    schedule: Yup.string().required(trans('common:formMessages.errorRequired')),
    phone: Yup.string()
      .min(10, trans('common:formMessages.errorPhone')) // Validación mínima para lada + número
      .required(trans('common:formMessages.errorRequired')),
    email: Yup.string()
      .email(trans('common:formMessages.errrorEmail'))
      .required(trans('common:formMessages.errorRequired'))
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
    handleErrors(e.target.name, '');
  };

  const handlePhoneChange = (value: string) => {
    setFormData({ ...formData, phone: value });
    handleErrors('phone', '');
  };

  const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault();
    setStatus('sending');
    
    const validateForm = await validationWithMessages(yupObjectShape, formData);

    if (validateForm?.isValid) {
      setErrors(INITIAL_ERRORS);

      const ahora = new Date();
      const fechaFormateada = ahora.toLocaleDateString('es-MX') + ' ' + ahora.toLocaleTimeString('es-MX', { hour: '2-digit', minute: '2-digit' });

      const pathParts = window.location.pathname.split('/').filter(p => p !== "");
      const proyectoDetectado = pathParts[pathParts.length - 1] || "Grupo Velas";

      // Formateamos el teléfono con un "+" para que sea legible
      const telefonoFinal = `+${formData.phone}`;

      const options = {
        method: "POST",
        url: apiContactMessages,
        headers: {
          Authorization: "Bearer " + apiToken,
          "Content-Type": "application/json"
        },
        data: {
          data: {
            ...formData,
            phone: telefonoFinal,
            phoneNumber: telefonoFinal,
            project: proyectoDetectado,
            submissionDate: fechaFormateada,
            type: "projects",
          }
        }
      };

      try {
        const response = await axios.request(options);
        if (response?.status === 200) {
          
          // Ejecutamos envíos externos
          await Promise.all([
            enviarCorreoAPI({ ...formData, phone: telefonoFinal }, proyectoDetectado, fechaFormateada),
            enviarGoogleSheets({
                ...formData,
                phone: telefonoFinal,
                project: proyectoDetectado,
                submissionDate: fechaFormateada
            })
          ]);

          setStatus('sended');
        } else {
          setStatus('loaded');
          setErrors({ ...INITIAL_ERRORS, general: trans('common:formMessages.generalError') });
        }
      } catch (error) {
        console.error(error);
        setStatus('loaded');
        setErrors({ ...INITIAL_ERRORS, general: trans('common:formMessages.generalError') });
      }
    } else {
      setStatus('loaded');
      setErrors({ ...INITIAL_ERRORS, ...validateForm?.errors });
    }
  };

  return (
    <div id="quote-form" className="quote-form" style={{ background: background || '#C6C4AF' }}>
      <style>{`
        .phone-input-custom .form-control {
          width: 100% !important;
          height: 58px !important;
          background: #fff !important;
          border: 1px solid #ced4da !important;
          border-radius: 0.375rem !important;
          font-family: 'Inter', sans-serif !important;
        }
        .phone-input-custom .flag-dropdown {
          background: transparent !important;
          border: none !important;
          border-radius: 0.375rem 0 0 0.375rem !important;
        }
      `}</style>

      <div className="container py-12">
        <div className="row g-7">
          <div className="col-12 col-md-5 col-lg-5 text-center text-md-start">
            <span className="base-pretitle"> {trans('projects:quote.preTitle')}</span>
            <h2 className="base-title tw-my-4">{trans('projects:quote.title')}</h2>
            <p className="base-text">{trans('projects:quote.text')}</p>
          </div>

          <div className="col-12 col-md-7 col-lg-6 offset-lg-1">
            {(status !== 'sended' && (
              <form className="contact-form needs-validation">
                <div className="messages">
                  {errors?.general && (
                    <p className="tw-text-xs tw-text-red-500 tw-font-inter mb-4 text-center">
                      {errors?.general}
                    </p>
                  )}
                </div>
                <div className="row gx-4">
                  {/* NOMBRE */}
                  <div className="col-md-6">
                    <div className="form-floating mb-4">
                      <input required type="text" name="name" id="form_name" 
                        placeholder={trans('projects:quote.name')}
                        className="form-control tw-text-sm"
                        value={formData.name} onChange={handleChange} />
                      <label htmlFor="form_name">{trans('projects:quote.name')} *</label>
                      {errors?.name && <p className="tw-text-xs tw-text-red-500 mt-1">{errors?.name}</p>}
                    </div>
                  </div>

                  {/* EMAIL */}
                  <div className="col-md-6">
                    <div className="form-floating mb-4">
                      <input required type="email" name="email" id="form_email"
                        className="form-control tw-text-sm"
                        placeholder="email@ejemplo.com"
                        value={formData.email} onChange={handleChange} />
                      <label htmlFor="form_email">{trans('projects:quote.email')} *</label>
                      {errors?.email && <p className="tw-text-xs tw-text-red-500 mt-1">{errors?.email}</p>}
                    </div>
                  </div>

                  {/* TELÉFONO CON LADA (PhoneInput) */}
                  <div className="col-md-12">
                    <div className="form-group mb-4 phone-input-custom">
                      <PhoneInput
                        country={'mx'}
                        value={formData.phone}
                        onChange={handlePhoneChange}
                        inputProps={{ name: 'phone', required: true, id: 'cel' }}
                        localization={{'Mexico': 'México'}}
                        placeholder={trans('projects:quote.phone')}
                      />
                      {errors?.phone && <p className="tw-text-xs tw-text-red-500 mt-1">{errors?.phone}</p>}
                    </div>
                  </div>

                  {/* HORARIO */}
                  <div className="col-md-12">
                    <div className="form-select-wrapper mb-4">
                      <select className="form-select" name="schedule" required 
                        value={formData.schedule} onChange={handleChange}>
                        <option disabled value="">{trans('projects:quote.schedule')} *</option>
                        {Array.isArray(schedules) && schedules.map((item: any, key: number) => (
                          <option value={item} key={key}>{item}</option>
                        ))}
                      </select>
                      {errors?.schedule && <p className="tw-text-xs tw-text-red-500 mt-1">{errors?.schedule}</p>}
                    </div>
                  </div>

                  {/* MENSAJE */}
                  <div className="col-12">
                    <div className="form-floating mb-4">
                      <textarea name="message" id="form_message"
                        className="form-control tw-text-sm"
                        value={formData.message} onChange={handleChange}
                        style={{ height: "100px" }} />
                      <label htmlFor="form_message">{trans('projects:quote.message')}</label>
                    </div>
                  </div>

                  {/* BOTÓN */}
                  <div className="col-12 text-center text-md-start">
                    {status === 'sending' ? (
                      <div className="mx-auto mx-md-0 tw-animate-bounce tw-max-w-max tw-rounded-md tw-bg-[#373A36] tw-text-white tw-font-semibold tw-text-xs tw-py-4 tw-px-8 tw-uppercase">
                        {trans('common:formMessages.sending')} ...
                      </div>
                    ) : (
                      <button onClick={handleSubmit}
                        className="tw-rounded-md tw-bg-[#373A36] tw-text-white tw-font-semibold tw-text-xs tw-py-4 tw-px-8 tw-uppercase hover:tw-bg-main-color">
                        {trans('projects:quote.btn')}
                      </button>
                    )}
                  </div>
                </div>
              </form>
            )) || ''}

            {status === 'sended' && (
              <div className="text-center py-12">
                <i className="tw-block mb-6 uil uil-check-circle tw-text-6xl tw-text-main-color"></i>
                <p className="tw-font-inter tw-text-4xl tw-text-secondary-dark">
                  {trans('common:formMessages.sended')}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ContactForm;