'use client';

import { useState, useRef } from 'react';
import { useTranslations, useLocale } from 'next-intl';
import { requestBrochureAction } from '@/app/actions/brochure';
import { cn } from '@/components/ui/utils';
import { useAnalytics } from './analytics/useAnalytics';
import { AnalyticsEvents } from './analytics/analytics-events';

interface Props {
  className?: string;
}

export default function FooterBrochureForm({ className }: Props) {
  const t = useTranslations('Brochure');
  const locale = useLocale();
  const { trackEvent } = useAnalytics();
  const formRef = useRef<HTMLFormElement>(null);

  const [phase, setPhase] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [err, setErr] = useState('');

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!formRef.current) return;
    setPhase('loading');

    const fd = new FormData(formRef.current);
    fd.set('locale', locale);

    try {
      const res = await requestBrochureAction(fd);
      if (res.success) {
        setPhase('success');
        trackEvent(AnalyticsEvents.DOWNLOAD, {
          file_name: `klz-product-catalog-${locale}.pdf`,
          file_type: 'brochure',
          location: 'footer_inline',
        });
      } else {
        setErr(res.error || 'Error');
        setPhase('error');
      }
    } catch {
      setErr('Network error');
      setPhase('error');
    }
  }

  if (phase === 'success') {
    return (
      <div
        className={cn(
          'flex flex-col sm:flex-row items-center gap-4 bg-white/5 border border-[#82ed20]/20 rounded-2xl p-6',
          className,
        )}
      >
        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#82ed20]/20 text-[#82ed20]">
          <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <div>
          <h4 className="text-white font-bold mb-1">
            {locale === 'de' ? 'Erfolgreich angefordert!' : 'Successfully requested!'}
          </h4>
          <p className="text-white/60 text-sm">
            {locale === 'de'
              ? 'Wir haben Ihnen den Katalog soeben per E-Mail zugesendet.'
              : 'We have just sent the catalog to your email.'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'bg-white/5 border border-white/10 rounded-3xl p-6 md:p-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-6 md:gap-12',
        className,
      )}
    >
      <div className="flex-1 max-w-xl">
        <h4 className="text-lg font-black text-white uppercase tracking-tight mb-2">
          {t('ctaTitle')}
        </h4>
        <p className="text-sm text-white/60 leading-relaxed mb-0">{t('subtitle')}</p>
      </div>

      <form
        ref={formRef}
        onSubmit={handleSubmit}
        className="w-full md:w-auto flex flex-col sm:flex-row gap-3"
      >
        {/* Anti-spam Honeypot */}
        <input
          type="text"
          name="company_website"
          tabIndex={-1}
          autoComplete="off"
          style={{ display: 'none' }}
          aria-hidden="true"
        />

        <div className="relative w-full sm:w-64">
          <input
            name="email"
            type="email"
            required
            placeholder={t('emailPlaceholder')}
            disabled={phase === 'loading'}
            className="w-full bg-primary-dark border border-white/20 rounded-xl px-4 py-3 text-sm text-white placeholder:text-white/30 focus:outline-none focus:border-[#82ed20]/50 transition-colors"
          />
        </div>
        <button
          type="submit"
          disabled={phase === 'loading'}
          className={cn(
            'flex items-center justify-center shrink-0 px-6 py-3 rounded-xl font-bold text-sm uppercase tracking-widest transition-colors',
            phase === 'loading'
              ? 'bg-white/10 text-white/40 cursor-wait'
              : 'bg-[#82ed20] text-[#000d26] hover:bg-[#6dd318] cursor-pointer',
          )}
        >
          {phase === 'loading' ? t('submitting') : t('submit')}
        </button>
      </form>
      {phase === 'error' && err && (
        <div className="absolute mt-16 text-red-400 text-xs font-medium">{err}</div>
      )}
    </div>
  );
}
