'use client';

import React, { useState } from 'react';
import { Mail, CheckCircle, AlertCircle, Loader2 } from 'lucide-react';

interface NewsletterProps {
  title?: string;
  subtitle?: string;
  placeholderText?: string;
  buttonText?: string;
  theme?: string;
}

export function Newsletter({
  title = 'ニュースレターに登録',
  subtitle = '最新の記事やお得な情報をメールでお届けします。',
  placeholderText = 'メールアドレスを入力',
  buttonText = '登録する',
  theme = 'default',
}: NewsletterProps) {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');

  const themeClasses: Record<string, { bg: string; card: string; input: string; btn: string; text: string; sub: string }> = {
    default: {
      bg: 'bg-gradient-to-br from-brand-primary/5 to-brand-accent/10',
      card: 'bg-dark-gray border border-soft-gray-border/20',
      input: 'bg-white border-soft-gray-border/30 text-white placeholder:text-text-light-gray focus:ring-brand-primary',
      btn: 'bg-crimson-red hover:bg-crimson-red/90 text-white',
      text: 'text-white',
      sub: 'text-text-light-gray',
    },
    warm: {
      bg: 'bg-gradient-to-br from-orange-50 to-amber-50',
      card: 'bg-white border border-orange-200',
      input: 'bg-orange-50/50 border-orange-200 text-slate-800 placeholder:text-slate-400 focus:ring-orange-500',
      btn: 'bg-orange-500 hover:bg-orange-600 text-white',
      text: 'text-slate-800',
      sub: 'text-slate-500',
    },
    professional: {
      bg: 'bg-gradient-to-br from-slate-800 to-slate-900',
      card: 'bg-slate-800/50 border border-slate-700',
      input: 'bg-slate-700 border-slate-600 text-white placeholder:text-slate-400 focus:ring-blue-400',
      btn: 'bg-white hover:bg-slate-100 text-slate-900',
      text: 'text-white',
      sub: 'text-slate-300',
    },
    ocean: {
      bg: 'bg-gradient-to-br from-blue-50 to-indigo-50',
      card: 'bg-white border border-blue-200',
      input: 'bg-blue-50/50 border-blue-200 text-slate-800 placeholder:text-slate-400 focus:ring-blue-500',
      btn: 'bg-blue-500 hover:bg-blue-600 text-white',
      text: 'text-slate-800',
      sub: 'text-slate-500',
    },
    forest: {
      bg: 'bg-gradient-to-br from-emerald-50 to-teal-50',
      card: 'bg-white border border-emerald-200',
      input: 'bg-emerald-50/50 border-emerald-200 text-slate-800 placeholder:text-slate-400 focus:ring-emerald-500',
      btn: 'bg-emerald-500 hover:bg-emerald-600 text-white',
      text: 'text-slate-800',
      sub: 'text-slate-500',
    },
  };
  const t = themeClasses[theme] || themeClasses.default;

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

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

      if (data.success) {
        setStatus('success');
        setMessage('登録ありがとうございます！');
        setEmail('');
      } else if (data.alreadyExists) {
        setStatus('error');
        setMessage('このメールアドレスは既に登録されています。');
      } else {
        setStatus('error');
        setMessage('登録に失敗しました。もう一度お試しください。');
      }
    } catch {
      setStatus('error');
      setMessage('エラーが発生しました。もう一度お試しください。');
    }
  };

  return (
    <section className={`w-full py-12 ${t.bg}`}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`${t.card} rounded-2xl p-8 sm:p-10 shadow-sm text-center`}>
          <div className="flex justify-center mb-4">
            <div className={`w-14 h-14 rounded-full ${theme === 'professional' ? 'bg-slate-700' : 'bg-crimson-red/10'} flex items-center justify-center`}>
              <Mail className={`w-7 h-7 ${theme === 'professional' ? 'text-blue-400' : 'text-crimson-red'}`} />
            </div>
          </div>
          <h2 className={`text-2xl font-bold mb-2 ${t.text}`}>{title}</h2>
          <p className={`text-sm mb-6 max-w-md mx-auto ${t.sub}`}>{subtitle}</p>

          {status === 'success' ? (
            <div className="flex items-center justify-center gap-2 text-emerald-600 font-medium py-4">
              <CheckCircle className="w-5 h-5" />
              <span>{message}</span>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="flex flex-col sm:flex-row gap-3 max-w-lg mx-auto">
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={placeholderText}
                required
                className={`flex-1 px-4 py-3 rounded-xl border ${t.input} focus:outline-none focus:ring-2 transition-colors text-sm`}
              />
              <button
                type="submit"
                disabled={status === 'loading'}
                className={`px-6 py-3 rounded-xl font-semibold text-sm ${t.btn} transition-colors disabled:opacity-50 flex items-center justify-center gap-2 shrink-0`}
              >
                {status === 'loading' ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  buttonText
                )}
              </button>
            </form>
          )}

          {status === 'error' && (
            <div className="flex items-center justify-center gap-2 text-red-500 text-sm mt-3">
              <AlertCircle className="w-4 h-4" />
              <span>{message}</span>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
