'use client';

import { useState, useEffect, useRef } from 'react';
import { getSalutations, getContextToken, type Salutation } from '@/lib/shopware-api';
import Captcha, { type CaptchaHandle } from '@/components/ui/Captcha';

interface Props {
  navigationId?: string;
  title?: string;
}

export default function CmsElementContactForm({ navigationId, title }: Props) {
  const [salutations, setSalutations] = useState<Salutation[]>([]);
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [error, setError] = useState('');

  const captchaRef = useRef<CaptchaHandle>(null);

  // Which fields the shop admin marked as required (Settings → Basic
  // information → Security and Privacy). Defaults keep them optional.
  const [required, setRequired] = useState({
    firstName: false,
    lastName: false,
    phone: false,
  });

  const [form, setForm] = useState({
    salutationId: '',
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    subject: '',
    comment: '',
  });

  useEffect(() => {
    getSalutations()
      .then((res) => {
        const list = res.elements.filter((s: Salutation) => s.salutationKey !== 'not_specified');
        setSalutations(list);
        if (list.length > 0) setForm((f) => ({ ...f, salutationId: list[0].id }));
      })
      .catch(() => {});

    fetch('/api/storefront-settings', { cache: 'no-store' })
      .then((res) => res.json())
      .then((s) =>
        setRequired({
          firstName: Boolean(s.firstNameFieldRequired),
          lastName: Boolean(s.lastNameFieldRequired),
          phone: Boolean(s.phoneNumberFieldRequired),
        })
      )
      .catch(() => {});
  }, []);

  function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) {
    setForm((f) => ({ ...f, [e.target.name]: e.target.value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setStatus('loading');
    setError('');
    try {
      const captchaPayload = (await captchaRef.current?.getPayload()) ?? {};

      const contextToken = getContextToken();
      const headers: Record<string, string> = { 'Content-Type': 'application/json' };
      if (contextToken) headers['sw-context-token'] = contextToken;

      const res = await fetch('/api/contact', {
        method: 'POST',
        headers,
        body: JSON.stringify({
          ...form,
          ...(navigationId ? { navigationId } : {}),
          ...captchaPayload,
        }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Something went wrong. Please try again.');
      }

      setStatus('success');
      setForm((f) => ({ ...f, firstName: '', lastName: '', email: '', phone: '', subject: '', comment: '' }));
      captchaRef.current?.reset();
    } catch (err: any) {
      setError(err.message || 'Something went wrong. Please try again.');
      setStatus('error');
      captchaRef.current?.reset();
    }
  }

  if (status === 'success') {
    return (
      <div className="max-w-2xl mx-auto py-12 text-center">
        <div className="text-5xl mb-4">✓</div>
        <h3 className="text-xl font-semibold text-surface-900 mb-2">Message sent!</h3>
        <p className="text-surface-500">We'll get back to you as soon as possible.</p>
        <button
          onClick={() => { setStatus('idle'); captchaRef.current?.reset(); }}
          className="mt-6 text-brand-600 hover:text-brand-700 text-sm font-medium"
        >
          Send another message
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      {title && <h2 className="text-2xl font-bold text-surface-900 mb-6">{title}</h2>}

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Row 1: Salutation, First name, Last name */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div>
            <label htmlFor="contact-salutation" className="block text-sm font-medium text-surface-700 mb-1">
              Salutation <span className="text-red-500">*</span>
            </label>
            <select
              id="contact-salutation"
              name="salutationId"
              value={form.salutationId}
              onChange={handleChange}
              required
              className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
            >
              {salutations.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.translated?.displayName ?? s.displayName}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label htmlFor="contact-firstName" className="block text-sm font-medium text-surface-700 mb-1">
              First name {required.firstName && <span className="text-red-500">*</span>}
            </label>
            <input
              id="contact-firstName"
              type="text"
              name="firstName"
              value={form.firstName}
              onChange={handleChange}
              required={required.firstName}
              autoComplete="given-name"
              className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
            />
          </div>

          <div>
            <label htmlFor="contact-lastName" className="block text-sm font-medium text-surface-700 mb-1">
              Last name {required.lastName && <span className="text-red-500">*</span>}
            </label>
            <input
              id="contact-lastName"
              type="text"
              name="lastName"
              value={form.lastName}
              onChange={handleChange}
              required={required.lastName}
              autoComplete="family-name"
              className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
            />
          </div>
        </div>

        {/* Row 2: Email, Phone */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label htmlFor="contact-email" className="block text-sm font-medium text-surface-700 mb-1">
              Email <span className="text-red-500">*</span>
            </label>
            <input
              id="contact-email"
              type="email"
              name="email"
              value={form.email}
              onChange={handleChange}
              required
              autoComplete="email"
              className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
            />
          </div>

          <div>
            <label htmlFor="contact-phone" className="block text-sm font-medium text-surface-700 mb-1">
              Phone {required.phone && <span className="text-red-500">*</span>}
            </label>
            <input
              id="contact-phone"
              type="tel"
              name="phone"
              value={form.phone}
              onChange={handleChange}
              required={required.phone}
              autoComplete="tel"
              className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
            />
          </div>
        </div>

        {/* Subject */}
        <div>
          <label htmlFor="contact-subject" className="block text-sm font-medium text-surface-700 mb-1">
            Subject <span className="text-red-500">*</span>
          </label>
          <input
            id="contact-subject"
            type="text"
            name="subject"
            value={form.subject}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
          />
        </div>

        {/* Message */}
        <div>
          <label htmlFor="contact-comment" className="block text-sm font-medium text-surface-700 mb-1">
            Message <span className="text-red-500">*</span>
          </label>
          <textarea
            id="contact-comment"
            name="comment"
            value={form.comment}
            onChange={handleChange}
            required
            rows={5}
            className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400 resize-none"
          />
        </div>

        {/* Captcha — renders whatever is active in Shopware admin */}
        <Captcha ref={captchaRef} action="contact" />

        <p className="text-xs text-surface-500">
          Fields marked with <span className="text-red-500">*</span> are required.
        </p>

        {status === 'error' && (
          <p className="text-sm text-red-500">{error}</p>
        )}

        <button
          type="submit"
          disabled={status === 'loading'}
          className="w-full sm:w-auto px-8 py-3 bg-brand-600 hover:bg-brand-700 text-white font-semibold rounded-xl transition-colors disabled:opacity-50"
        >
          {status === 'loading' ? 'Sending...' : 'Send message'}
        </button>
      </form>
    </div>
  );
}
