"use client";

import Image from 'next/image';
import { useState, useRef } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import styles from './LocationSection.module.css';

export default function LocationSection() {
  const [formData, setFormData] = useState({
    name: '',
    lastName: '',
    email: '',
    message: '',
  });
  const [captchaToken, setCaptchaToken] = useState(null);
  const [formStatus, setFormStatus] = useState({ show: false, type: '', message: '' });
  const recaptchaRef = useRef(null);

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

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

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

    if (!formData.name || !formData.email || !formData.message) {
      setFormStatus({ show: true, type: 'danger', message: 'Please fill in all required fields.' });
      return;
    }

    if (!captchaToken) {
      setFormStatus({ show: true, type: 'danger', message: 'Please verify the CAPTCHA.' });
      return;
    }

    const emailData = {
      ...formData,
      subject: `Message from ${formData.name} ${formData.lastName}`,
      recaptchaToken: captchaToken,
      to: 'mydosaplacewaterloo@gmail.com',
      senderName: 'My Dosa Place Home Contact Form',
      message: `
        <b>Name:</b> ${formData.name} ${formData.lastName}<br/>
        <b>Email:</b> ${formData.email}<br/>
        <b>Message:</b><br/>${formData.message}
      `,
    };

    try {
      const response = await fetch('https://mailserver.metatronnest.com/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(emailData),
      });

      if (!response.ok) {
        throw new Error('Failed to send message');
      }

      setFormStatus({ show: true, type: 'success', message: 'Your message has been sent successfully!' });
      setFormData({ name: '', lastName: '', email: '', message: '' });
      setCaptchaToken(null);
      if (recaptchaRef.current) {
        recaptchaRef.current.reset();
      }
    } catch {
      setFormStatus({ show: true, type: 'danger', message: 'Failed to send your message. Try again later.' });
    }
  };

  return (
    <section id="contact" className={styles.section}>
      <div className={styles.container}>
        <div className={styles.header}>
          {/* <p className={styles.sectionTag}>📍 Contact & Location</p> */}
          <span className={styles.eyebrow}>
            <span className={styles.eyebrowIcon}>📍</span> Find Us
          </span>
          <h2 className={styles.sectionTitle}>
            Visit Our <em>Restaurant</em>
          </h2>
          <p className={styles.sectionDesc}>We'd love to hear from you. Book a table or ask us a question.</p>
        </div>

        <div className={styles.premiumCard}>
          {/* Left - Image & Glass Info */}
          <div className={styles.imagePane}>
            <Image 
              src="/images/hero-dosa.png" 
              alt="Restaurant ambiance" 
              fill 
              className={styles.bgImage} 
            />
            <div className={styles.imageOverlay}></div>
            
            <div className={styles.glassInfo}>
              <div className={styles.infoItem}>
                <div className={styles.infoIcon}>
                  <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path><circle cx="12" cy="10" r="3"></circle></svg>
                </div>
                <div>
                  <h4 className={styles.infoLabel}>Our Location</h4>
                  <p className={styles.infoText}>
                    922 Erb St. W Unit C3#3,<br />
                    Waterloo, ON N2T 0C9
                  </p>
                </div>
              </div>

              <div className={styles.infoItem}>
                <div className={styles.infoIcon}>
                  <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                </div>
                <div>
                  <h4 className={styles.infoLabel}>Opening Hours</h4>
                  <p className={styles.infoText}>
                    Sun: 12 PM – 9 PM<br />
                    Mon: 4 PM – 10 PM<br />
                    Tue: Closed<br />
                    Wed & Sat: 12 PM – 10 PM<br />
                    Thu & Fri: 5 PM – 10 PM
                  </p>
                </div>
              </div>

              <div className={styles.infoItem}>
                <div className={styles.infoIcon}>
                  <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" viewBox="0 0 24 24"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path></svg>
                </div>
                <div>
                  <h4 className={styles.infoLabel}>Contact Us</h4>
                  <p className={styles.infoText}>
                    +1 (519) 888-7459<br />
                    mydosaplacewaterloo@gmail.com
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Right - Contact Form */}
          <div className={styles.formPane}>
            <h3 className={styles.formTitle}>Send a Message</h3>
            <p className={styles.formSubtitle}>Fill out the form below and our team will get back to you shortly.</p>

            {formStatus.show && (
              <div className={`${styles.formMessage} ${formStatus.type === 'success' ? styles.success : styles.error}`}>
                {formStatus.message}
              </div>
            )}
            
            <form className={styles.form} onSubmit={handleSubmit}>
              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <label htmlFor="name" className={styles.label}>First Name</label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    className={styles.input}
                    placeholder="John"
                    value={formData.name}
                    onChange={handleChange}
                  />
                </div>
                <div className={styles.formGroup}>
                  <label htmlFor="lastName" className={styles.label}>Last Name</label>
                  <input
                    type="text"
                    id="lastName"
                    name="lastName"
                    className={styles.input}
                    placeholder="Doe"
                    value={formData.lastName}
                    onChange={handleChange}
                  />
                </div>
              </div>
              
              <div className={styles.formGroup}>
                <label htmlFor="email" className={styles.label}>Email Address</label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  className={styles.input}
                  placeholder="john@example.com"
                  value={formData.email}
                  onChange={handleChange}
                />
              </div>
              
              <div className={styles.formGroup}>
                <label htmlFor="message" className={styles.label}>Your Message</label>
                <textarea
                  id="message"
                  name="message"
                  rows="4"
                  className={styles.textarea}
                  placeholder="How can we help you?"
                  value={formData.message}
                  onChange={handleChange}
                ></textarea>
              </div>

              <div className={styles.captchaWrapper}>
                <ReCAPTCHA
                  ref={recaptchaRef}
                  sitekey="6LeaPggsAAAAAM4DHBSX0y3IC6lu9SrJIhoQKZKo"
                  onChange={handleCaptchaChange}
                />
              </div>
              
              <button type="submit" className={styles.btnSubmit}>
                Send Message
              </button>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}
