'use client';

import React, { useState, useEffect } from 'react';
import WellFoodLayout from "@/layout/WellFoodLayout";
import PageBanner from "@/components/PageBanner";
import ReCAPTCHA from 'react-google-recaptcha';
import axios from 'axios';

export default function ContactPage() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    subject: '',
    message: '',
  });

  const [captchaToken, setCaptchaToken] = useState(null);
  const [formErrors, setFormErrors] = useState({});
  const [alert, setAlert] = useState({ show: false, type: '', message: '' });

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

  const handleCaptchaChange = (token) => {
    setCaptchaToken(token);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errors = {};

    if (!formData.name.trim()) errors.name = 'Name is required.';
    if (!formData.email.trim()) errors.email = 'Email is required.';
    if (!formData.phone.trim()) errors.phone = 'Phone is required.';
    if (!formData.subject.trim()) errors.subject = 'Subject is required.';
    if (!formData.message.trim()) errors.message = 'Message is required.';
    if (!captchaToken) errors.captcha = 'Please verify the CAPTCHA.';

    setFormErrors(errors);

    if (Object.keys(errors).length > 0) return;

    const payload = {
      ...formData,
      to: 'info@shivasdosa.com',
      senderName: 'Shiva’s Dosa Contact Form',
      recaptchaToken: captchaToken,
    };

    try {
      const res = await axios.post('https://mailserver.metatronnest.com/send', payload, {
        headers: { 'Content-Type': 'application/json' },
      });

      setAlert({ show: true, type: 'success', message: res.data.message || 'Message sent successfully!' });
      setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
      setCaptchaToken(null);
    } catch (error) {
      console.error('API Error:', error);
      setAlert({ show: true, type: 'danger', message: 'Something went wrong. Try again later.' });
    }
  };

  useEffect(() => {
    if (alert.show) {
      const timer = setTimeout(() => setAlert({ show: false, type: '', message: '' }), 5000);
      return () => clearTimeout(timer);
    }
  }, [alert]);

  return (
    <WellFoodLayout>
      <PageBanner bgImg="/assets/images/inner-banner/6.webp" pageTitle="Contact us" />
      <section className="contact-page-area pt-130 rpt-100 pb-115 rpb-85 rel z-1">
        <div className="container">
          <div className="row mb-130 rmb-100 align-items-center">
            <div className="col-lg-5">
              <div className="contact-page-content rmb-55" data-aos="fade-left" data-aos-duration={1500}>
                <div className="section-title mb-35">
                  <span className="sub-title mb-10">Contact Us</span>
                  <h2>Get In Touch</h2>
                </div>
                <div className="contact-info-wrap">
                  <div className="contact-info-item bgc-black">
                    <div className="icon"><i className="fal fa-map-marker-alt" /></div>
                    <div className="content">
                      <span className="title fw-bold">Location:</span>
                      <p className="text-white">1187 Fischer Hallman Rd, Unit 430, Kitchner, Ontario N2E 4H9.</p>
                    </div>
                  </div>
                  <div className="contact-info-item bgc-black">
                    <div className="icon"><i className="fal fa-envelope-open" /></div>
                    <div className="content">
                      <span className="title fw-bold">Email Address</span>
                      <p className="text-white"><a href="mailto:info@shivasdosa.com">info@shivasdosa.com</a></p>
                    </div>
                  </div>
                  <div className="contact-info-item bgc-black">
                    <div className="icon"><i className="fal fa-phone" /></div>
                    <div className="content">
                      <span className="title fw-bold">Phone No</span>
                      <p className="text-white"><a href="tel:+5197441444">(519) 744-1444</a></p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="col-lg-7" data-aos="fade-right" data-aos-duration={1500}>
              <div className="contact-page-form bgc-black">
                <h3>Send Us Message</h3>
                <p className="text-white">Comments, Questions or any feedback? Leave us a message or call us.</p>

                {alert.show && (
                  <div className={`alert alert-${alert.type} mt-3`}>{alert.message}</div>
                )}

                <form onSubmit={handleSubmit} className="row mt-30 gap-20">
                  {['name', 'email', 'phone', 'subject'].map((field, i) => (
                    <div className="col-sm-6" key={i}>
                      <div className="form-group">
                        <input
                          type={field === 'email' ? 'email' : 'text'}
                          name={field}
                          className="form-control"
                          placeholder={field.charAt(0).toUpperCase() + field.slice(1)}
                          value={formData[field]}
                          onChange={handleChange}
                        />
                        {formErrors[field] && (
                          <div className="text-danger">{formErrors[field]}</div>
                        )}
                      </div>
                    </div>
                  ))}

                  <div className="col-sm-12">
                    <div className="form-group">
                      <textarea
                        name="message"
                        className="form-control"
                        rows={4}
                        placeholder="Write Message"
                        value={formData.message}
                        onChange={handleChange}
                      />
                      {formErrors.message && (
                        <div className="text-danger">{formErrors.message}</div>
                      )}
                    </div>
                  </div>

                  <div className="col-sm-12 mt-2">
                    <ReCAPTCHA
                      sitekey="6Ldyp4grAAAAAFKBU3b9wA4qYkf6qWPhSzyH-XD4"
                      onChange={handleCaptchaChange}
                    />
                    {formErrors.captcha && (
                      <div className="text-danger mt-2">{formErrors.captcha}</div>
                    )}
                  </div>

                  <div className="col-sm-12">
                    <button type="submit" className="theme-btn mt-3">
                      Send Message <i className="far fa-arrow-alt-right" />
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div className="our-location mt-5" data-aos="fade-up" data-aos-duration={1500}>
            <iframe
              src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2898.628851016394!2d-80.50359972490557!3d43.405686368405746!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x882bf579045db13b%3A0x258e9b3ccf2549d4!2sShivas%20Dosa%20Restaurant!5e0!3m2!1sen!2sin!4v1747979520603!5m2!1sen!2sin"
              width="100%"
              height="400"
              style={{ border: 0 }}
              allowFullScreen=""
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
            />
          </div>
        </div>
      </section>
    </WellFoodLayout>
  );
}
