'use client';

import { useState, type FormEvent } from 'react';
import Link from 'next/link';
import type { LeadSource } from '@/lib/leads';

interface Props {
  source: LeadSource;
  resultCode?: string;
  buttonLabel: string;
  consentText: string;
  successText: string;
}

export function EmailCapture({ source, resultCode, buttonLabel, consentText, successText }: Props) {
  const [status, setStatus] = useState<'idle' | 'sending' | 'done' | 'error'>('idle');
  const [error, setError] = useState('');

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    setStatus('sending');
    setError('');
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: String(form.get('email') ?? '').trim(),
          consent: form.get('consent') === 'on',
          company: String(form.get('company') ?? ''),
          source,
          resultCode,
        }),
      });
      if (!res.ok) {
        const body = (await res.json().catch(() => null)) as { error?: string } | null;
        throw new Error(body?.error ?? 'Something went wrong. Please try again.');
      }
      setStatus('done');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong. Please try again.');
      setStatus('error');
    }
  }

  if (status === 'done') {
    return (
      <p className="form-msg ok" role="status">
        {successText}
      </p>
    );
  }

  return (
    <form className="form" onSubmit={onSubmit} noValidate>
      <div className="form-row">
        <label htmlFor={`email-${source}`} className="sr-only">
          Email address
        </label>
        <input
          id={`email-${source}`}
          className="input"
          type="email"
          name="email"
          autoComplete="email"
          placeholder="you@example.com"
          required
        />
        <button className="btn btn-primary" type="submit" disabled={status === 'sending'}>
          {status === 'sending' ? 'Saving…' : buttonLabel}
        </button>
      </div>
      {/* Honeypot: real people never see or fill this. */}
      <div className="hp" aria-hidden="true">
        <label>
          Company
          <input type="text" name="company" tabIndex={-1} autoComplete="off" />
        </label>
      </div>
      <label className="checkbox">
        <input type="checkbox" name="consent" required />
        <span>
          {consentText} See our <Link href="/legal">privacy notice</Link>.
        </span>
      </label>
      {status === 'error' && (
        <p className="form-msg err" role="alert">
          {error}
        </p>
      )}
    </form>
  );
}
