'use client';

import { useState } from 'react';
import { ArrowRight, Loader2 } from 'lucide-react';

type Status = 'idle' | 'loading' | 'success' | 'error' | 'not-configured';

export function NewsletterForm() {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<Status>('idle');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email.trim() || status === 'loading') return;

    setStatus('loading');

    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();

      if (data.ok) {
        setStatus('success');
      } else if (data.error === 'not_configured') {
        setStatus('not-configured');
      } else {
        setStatus('error');
      }
    } catch {
      setStatus('error');
    }
  };

  if (status === 'success') {
    return (
      <p className="text-white-dim text-sm font-medium tracking-wide">
        Good. You&apos;ll hear from this side when there&apos;s something worth saying.
      </p>
    );
  }

  if (status === 'not-configured') {
    return (
      <p className="text-white-muted text-sm leading-relaxed max-w-md">
        The newsletter isn&apos;t connected to a provider yet — add{' '}
        <code className="text-white-dim">BUTTONDOWN_API_KEY</code> to your environment
        variables to start collecting real subscribers.
      </p>
    );
  }

  return (
    <div className="max-w-md">
      <form onSubmit={handleSubmit} className="flex gap-0">
        <input
          type="email"
          required
          value={email}
          onChange={e => setEmail(e.target.value)}
          placeholder="Your email"
          disabled={status === 'loading'}
          className="flex-1 bg-surface-raised border border-subtle px-4 py-3 text-white-primary text-sm placeholder:text-white-muted focus:outline-none focus:border-white-dim transition-colors duration-200 rounded-l-none rounded-r-none disabled:opacity-60"
          style={{ borderRight: 'none', borderColor: 'hsl(0 0% 13%)' }}
        />
        <button
          type="submit"
          disabled={status === 'loading'}
          className="border px-5 py-3 text-white-dim text-sm tracking-wide transition-all duration-200 flex items-center gap-2 hover:text-white-primary hover:border-white-dim disabled:opacity-60"
          style={{
            backgroundColor: 'hsl(0 0% 10%)',
            borderColor: 'hsl(0 0% 13%)',
          }}
        >
          {status === 'loading' ? (
            <Loader2 size={15} className="animate-spin" />
          ) : (
            <ArrowRight size={15} />
          )}
        </button>
      </form>
      {status === 'error' && (
        <p className="text-white-muted text-xs mt-3">
          That didn&apos;t go through — mind trying again in a moment?
        </p>
      )}
    </div>
  );
}
