"use client";

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

import { useT } from "@/context/I18nContext"; 

export default function ContactForm() {
     const formRef = useRef();
     const [success, setSuccess] = useState(null);
     const [showMessage, setShowMessage] = useState(false);
     const [isSubmitting, setIsSubmitting] = useState(false);
     const [errorMessage, setErrorMessage] = useState('');
     const [compliance, setCompliance] = useState(false); 

     const { t } = useT(); 

     const handleShowMessage = (message = '') => {
          setErrorMessage(message);
          setShowMessage(true);
          setTimeout(() => {
               setShowMessage(false);
               setErrorMessage('');
          }, 4000);
     };

     const sendMail = async (e) => {
          e.preventDefault();
          
          if(!compliance) {
               handleShowMessage('Te rugăm să accepți prelucrarea datelor personale.');
               return; 
          }

          setIsSubmitting(true);

          try {
               const formData = new FormData(formRef.current);
               const data = {
                    name: formData.get('name')?.trim(),
                    email: formData.get('email')?.trim(),
                    message: formData.get('message')?.trim(),
               };

               // Validare client-side
               if (!data.name || !data.email || !data.message) {
                    handleShowMessage('Toate câmpurile sunt obligatorii');
                    setSuccess(false);
                    setIsSubmitting(false);
                    return;
               }

               const response = await fetch('/api/contact', {
                    method: 'POST',
                    headers: {
                         'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
               });

               const result = await response.json();

               if (response.ok) {
                    setSuccess(true);
                    formRef.current.reset();
                    handleShowMessage('');
               } else {
                    setSuccess(false);
                    handleShowMessage(result.error || 'A apărut o eroare');
               }

          } catch (error) {
               console.error('Error:', error);
               setSuccess(false);
               handleShowMessage('Eroare de conexiune. Te rugăm să reîncerci.');
          } finally {
               setIsSubmitting(false);
          }
     };

     return (
          <section className='flat-spacing-21'>
               <center>
                    <div className='container'>
                         <div className='tf-grid-layout gap30 lg-col-12' style={{ paddingRight: 300, paddingLeft: 300 }}>
                              <div>
                                   <form
                                        ref={formRef}
                                        onSubmit={sendMail}
                                        className='form-contact'
                                   >
                                        <div className='d-flex gap-15 mb_15'>
                                             <fieldset className='w-100'>
                                                  <input
                                                       type='text'
                                                       name='name'
                                                       required
                                                       placeholder={t("contact_nume")}
                                                       maxLength={100}
                                                       disabled={isSubmitting}
                                                  />
                                             </fieldset>
                                             <fieldset className='w-100'>
                                                  <input
                                                       type='email'
                                                       name='email'
                                                       required
                                                       placeholder='Email *'
                                                       maxLength={100}
                                                       disabled={isSubmitting}
                                                  />
                                             </fieldset>
                                        </div>
                                        <div className='mb_15'>
                                             <textarea
                                                  placeholder={"contact_mesaj"}
                                                  name='message'
                                                  required
                                                  cols={30}
                                                  rows={10}
                                                  maxLength={2000}
                                                  disabled={isSubmitting}
                                             />
                                        </div>

                                        {showMessage && (
                                             <div className='tfSubscribeMsg active'>
                                                  {success ? (
                                                       <p style={{ color: "rgb(52, 168, 83)" }}>
                                                            ✅ Mesajul a fost trimis cu succes!
                                                       </p>
                                                  ) : (
                                                       <p style={{ color: "red" }}>
                                                            ❌ {errorMessage || 'Oops! Ceva nu a mers bine, te rugăm să reîncerci.'}
                                                       </p>
                                                  )}
                                             </div>
                                        )}

                                        <div className='send-wrap'>
                                             <div className='mb_15 d-flex align-items-center'>
                                                  <input
                                                       type='checkbox'
                                                       name='compliance'
                                                       checked={compliance}
                                                       onChange={(e) => setCompliance(e.target.checked)}
                                                  />
                                                  <label htmlFor='compliance' className='ml_10'>
                                                       {t("contact_bifa")}
                                                       <a href="/politica-de-confidentialitate">{t("politica_de_confidentialitate")}</a>.
                                                  </label>
                                             </div>
                                             <button
                                                  type='submit'
                                                  className='tf-btn w-100 radius-3 btn-fill animate-hover-btn justify-content-center'
                                                  disabled={isSubmitting}
                                             >
                                                  {isSubmitting ? t("contact_button_sending") : t("contact_button")}
                                             </button>
                                        </div>
                                   </form>
                              </div>
                         </div>
                    </div>
               </center>
          </section>
     );
}