'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

const defaultServiceOptions = [
  'Crystal Therapy',
  'Temazcal / Sweat Lodge',
  'Premium Transformational Session',
];

export default function ContactPage() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [service, setService] = useState('');
  const [message, setMessage] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState('');
  const [serviceOptions, setServiceOptions] = useState(defaultServiceOptions);

  useEffect(() => {
    fetch('/api/cms/services')
      .then((res) => res.ok ? res.json() : null)
      .then((data) => {
        if (data?.services?.length) {
          const names = data.services.map((s: { title: string }) => s.title);
          setServiceOptions(names);
        }
      })
      .catch(() => {});
  }, []);

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

    if (!name.trim() || !email.trim() || !message.trim()) {
      setStatus('error');
      setErrorMessage('Please fill in all required fields.');
      return;
    }

    setStatus('loading');
    setErrorMessage('');

    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim(),
          service: service || undefined,
          message: message.trim(),
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || 'Something went wrong');
      }

      setStatus('success');
      setName('');
      setEmail('');
      setService('');
      setMessage('');
    } catch (err) {
      setStatus('error');
      setErrorMessage(err instanceof Error ? err.message : 'Failed to send message. Please try again.');
    }
  };

  return (
    <>
      {/* Page Hero */}
      <section className="page-hero relative flex flex-col items-center justify-center text-center px-6">
        <div className="absolute inset-0 z-0 bg-gradient-to-b from-[var(--bg-cream)] via-white to-[var(--bg-cream)]" />
        <div className="relative z-10 max-w-4xl mx-auto">
          <p className="font-sans-alt text-xs tracking-[0.2em] text-[var(--accent-gold)] mb-4">
            GET IN TOUCH
          </p>
          <h1 className="text-5xl md:text-6xl font-light tracking-wider mb-4">
            Contact Now
          </h1>
          <p className="text-2xl font-light tracking-wider mb-6 opacity-70">
            XHIVA
          </p>
          <div className="divider"></div>
          <p className="text-lg md:text-xl max-w-2xl mx-auto leading-relaxed opacity-80">
            For inquiries about sessions, art commissions, or event collaborations,
            please reach out through the form below or connect on social media.
          </p>
        </div>
      </section>

      {/* Contact Form + Sidebar */}
      <section className="section bg-white">
        <div className="max-w-6xl mx-auto">
          <div className="grid md:grid-cols-3 gap-12">
            {/* Form */}
            <div className="md:col-span-2">
              {status === 'success' ? (
                <div className="text-center py-12">
                  <div className="text-5xl mb-6 text-[var(--accent-gold)]">&#10003;</div>
                  <h3 className="text-2xl font-light mb-4">Message Sent</h3>
                  <p className="text-lg opacity-80 mb-8">
                    Thank you for reaching out. I will get back to you soon.
                  </p>
                  <button
                    onClick={() => setStatus('idle')}
                    className="btn-outline"
                  >
                    Send Another Message
                  </button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="text-left">
                  <div className="mb-6">
                    <label className="block font-sans-alt text-xs tracking-widest mb-2" htmlFor="name">
                      NAME *
                    </label>
                    <input
                      type="text"
                      id="name"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-[var(--accent-gold)] transition-colors"
                      placeholder="Your name"
                      disabled={status === 'loading'}
                    />
                  </div>
                  <div className="mb-6">
                    <label className="block font-sans-alt text-xs tracking-widest mb-2" htmlFor="email">
                      EMAIL *
                    </label>
                    <input
                      type="email"
                      id="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-[var(--accent-gold)] transition-colors"
                      placeholder="your@email.com"
                      disabled={status === 'loading'}
                    />
                  </div>
                  <div className="mb-6">
                    <label className="block font-sans-alt text-xs tracking-widest mb-2" htmlFor="service">
                      SERVICE
                    </label>
                    <select
                      id="service"
                      value={service}
                      onChange={(e) => setService(e.target.value)}
                      className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-[var(--accent-gold)] transition-colors bg-white"
                      disabled={status === 'loading'}
                    >
                      <option value="">Which service do you want to book?</option>
                      {serviceOptions.map((opt) => (
                        <option key={opt} value={opt}>{opt}</option>
                      ))}
                    </select>
                  </div>
                  <div className="mb-6">
                    <label className="block font-sans-alt text-xs tracking-widest mb-2" htmlFor="message">
                      MESSAGE *
                    </label>
                    <textarea
                      id="message"
                      rows={6}
                      value={message}
                      onChange={(e) => setMessage(e.target.value)}
                      className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-[var(--accent-gold)] transition-colors resize-none"
                      placeholder="How can I support your journey?"
                      disabled={status === 'loading'}
                    />
                  </div>

                  {status === 'error' && errorMessage && (
                    <p className="text-red-600 text-sm mb-4 font-sans-alt">{errorMessage}</p>
                  )}

                  <button
                    type="submit"
                    className="btn-filled w-full mt-4"
                    disabled={status === 'loading'}
                    style={status === 'loading' ? { opacity: 0.7, cursor: 'not-allowed' } : undefined}
                  >
                    {status === 'loading' ? 'Sending...' : 'Send Message'}
                  </button>
                </form>
              )}
            </div>

            {/* Sidebar */}
            <div className="text-center md:text-left">
              <h3 className="text-2xl font-light mb-6">Connect</h3>
              <div className="space-y-6">
                <div>
                  <p className="font-sans-alt text-xs tracking-widest text-[var(--accent-gold)] mb-2">
                    INSTAGRAM
                  </p>
                  <a
                    href="https://instagram.com/ximena_xaguar"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[var(--text-dark)] hover:text-[var(--accent-gold)] transition-colors"
                  >
                    @ximena_xaguar
                  </a>
                </div>
                <div>
                  <p className="font-sans-alt text-xs tracking-widest text-[var(--accent-gold)] mb-2">
                    XHIVA ART
                  </p>
                  <a
                    href="https://instagram.com/xhiva_art"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[var(--text-dark)] hover:text-[var(--accent-gold)] transition-colors"
                  >
                    @xhiva_art
                  </a>
                </div>
                <div>
                  <p className="font-sans-alt text-xs tracking-widest text-[var(--accent-gold)] mb-2">
                    RE EVOLUTION ART
                  </p>
                  <a
                    href="https://instagram.com/reevolutionart"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[var(--text-dark)] hover:text-[var(--accent-gold)] transition-colors"
                  >
                    @reevolutionart
                  </a>
                </div>
                <div>
                  <p className="font-sans-alt text-xs tracking-widest text-[var(--accent-gold)] mb-2">
                    FACEBOOK
                  </p>
                  <a
                    href="https://www.facebook.com/XimenaXhivart"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[var(--text-dark)] hover:text-[var(--accent-gold)] transition-colors"
                  >
                    Ximena Xhivart
                  </a>
                </div>
                <div>
                  <p className="font-sans-alt text-xs tracking-widest text-[var(--accent-gold)] mb-2">
                    SOUNDCLOUD
                  </p>
                  <a
                    href="https://soundcloud.com/xhiva"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[var(--text-dark)] hover:text-[var(--accent-gold)] transition-colors"
                  >
                    XHIVA
                  </a>
                </div>
              </div>

              <div className="mt-10">
                <Link href="/services" className="btn-outline text-sm">
                  View Sessions & Pricing
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
