'use client';

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

interface Props {
  title?: string;
}

export default function CmsElementNewsletterForm({ title }: Props) {
  const [salutations, setSalutations] = useState<Salutation[]>([]);
  const [action, setAction] = useState<'subscribe' | 'unsubscribe'>('subscribe');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [error, setError] = useState('');
  const [privacyAccepted, setPrivacyAccepted] = useState(false);
  const captchaRef = useRef<CaptchaHandle>(null);

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

  useEffect(() => {
    getSalutations()
      .then((res) => {
        setSalutations(res.elements);
        const notSpecified = res.elements.find((s) => s.salutationKey === 'not_specified');
        if (notSpecified) setForm((f) => ({ ...f, salutationId: notSpecified.id }));
      })
      .catch(() => {});
  }, []);

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (action === 'subscribe' && !privacyAccepted) {
      setError('Please accept the privacy policy.');
      return;
    }
    setStatus('loading');
    setError('');
    try {
      // CAPTCHA applies to subscribe (Shopware doesn't gate unsubscribe).
      if (action === 'subscribe') {
        const captchaPayload = (await captchaRef.current?.getPayload()) ?? {};
        await runCaptchaGate(captchaPayload);
      }
      await subscribeNewsletter(form.email, action, {
        salutationId: form.salutationId || undefined,
        firstName: form.firstName || undefined,
        lastName: form.lastName || undefined,
      });
      setStatus('success');
    } 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-xl mx-auto py-10 text-center">
        <div className="text-5xl mb-4">✓</div>
        <h3 className="text-xl font-semibold text-surface-900 mb-2">
          {action === 'subscribe' ? 'Almost there!' : 'Unsubscribed'}
        </h3>
        <p className="text-surface-500">
          {action === 'subscribe'
            ? 'Check your email to confirm your subscription.'
            : 'You have been unsubscribed from the newsletter.'}
        </p>
        <button
          onClick={() => {
            setStatus('idle');
            setPrivacyAccepted(false);
            setForm((f) => ({ ...f, email: '', firstName: '', lastName: '' }));
          }}
          className="mt-6 text-brand-600 hover:text-brand-700 text-sm font-medium"
        >
          Back
        </button>
      </div>
    );
  }

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

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Action */}
        <div>
          <label className="block text-sm font-medium text-surface-700 mb-1">
            Action <span className="text-red-500">*</span>
          </label>
          <select
            value={action}
            onChange={(e) => {
              setAction(e.target.value as 'subscribe' | 'unsubscribe');
              setError('');
            }}
            className="w-full px-3 py-2 border border-surface-200 rounded-lg text-sm focus:outline-none focus:border-brand-400"
          >
            <option value="subscribe">Subscribe to newsletter</option>
            <option value="unsubscribe">Unsubscribe from newsletter</option>
          </select>
        </div>

        {/* Email */}
        <div>
          <label className="block text-sm font-medium text-surface-700 mb-1">
            Email address <span className="text-red-500">*</span>
          </label>
          <input
            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>

        {/* Additional fields — subscribe only */}
        {action === 'subscribe' && (
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-surface-700 mb-1">Salutation</label>
              <select
                name="salutationId"
                value={form.salutationId}
                onChange={handleChange}
                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 className="block text-sm font-medium text-surface-700 mb-1">First name</label>
              <input
                type="text"
                name="firstName"
                value={form.firstName}
                onChange={handleChange}
                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 className="block text-sm font-medium text-surface-700 mb-1">Last name</label>
              <input
                type="text"
                name="lastName"
                value={form.lastName}
                onChange={handleChange}
                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>
        )}

        {/* Privacy — subscribe only */}
        {action === 'subscribe' && (
          <div className="flex items-start gap-3">
            <input
              type="checkbox"
              id="nl-privacy"
              checked={privacyAccepted}
              onChange={(e) => setPrivacyAccepted(e.target.checked)}
              className="mt-0.5 w-4 h-4 rounded border-surface-300 text-brand-600 focus:ring-brand-400"
            />
            <label htmlFor="nl-privacy" className="text-sm text-surface-600">
              I have read the data protection information. <span className="text-red-500">*</span>
            </label>
          </div>
        )}

        {/* Captcha — subscribe only, renders whatever is active in admin */}
        {action === 'subscribe' && <Captcha ref={captchaRef} action="newsletter" />}

        <p className="text-xs text-surface-400">
          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'}
        </button>
      </form>
    </div>
  );
}
