import React, { useState } from 'react';
import { toast } from 'sonner';

interface NewsletterFormProps {
  description?: string;
  gdprRequired?: boolean;
  consentText?: string;
}

export function NewsletterForm({
  description,
  gdprRequired = false,
  consentText = 'I agree to receive marketing emails and understand I can unsubscribe at any time.',
}: NewsletterFormProps) {
  const [email, setEmail] = useState('');
  const [consent, setConsent] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!email || !email.includes('@')) {
      toast.error('Please enter a valid email address');
      return;
    }

    if (gdprRequired && !consent) {
      toast.error('Please accept the terms to subscribe');
      return;
    }

    setLoading(true);
    try {
      const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
      const response = await fetch(`${apiRoot}/newsletter/subscribe`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ email, consent }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(data.message || 'Successfully subscribed to newsletter!');
        setEmail('');
        setConsent(false);
      } else {
        toast.error(data.message || 'Failed to subscribe. Please try again.');
      }
    } catch (error) {
      console.error('Newsletter subscription error:', error);
      toast.error('An error occurred. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      {description && <p className="text-sm text-gray-600 mb-4">{description}</p>}
      <form onSubmit={handleSubmit} className="space-y-3">
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Your email"
          className="w-full px-4 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-primary"
          disabled={loading}
        />

        {gdprRequired && (
          <label className="flex items-start gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={consent}
              onChange={(e) => setConsent(e.target.checked)}
              className="mt-1 rounded border-gray-300"
              disabled={loading}
            />
            <span className="text-xs text-gray-600 leading-relaxed">
              {consentText}
            </span>
          </label>
        )}

        <button
          type="submit"
          disabled={loading || (gdprRequired && !consent)}
          className="font-[inherit] w-full px-4 py-2 bg-gray-900 text-white text-sm font-medium rounded-md hover:bg-gray-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? 'Subscribing...' : 'Subscribe'}
        </button>
      </form>
    </div>
  );
}
