'use client';

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

interface NewsletterInlineProps {
  title?: string;
  description?: string;
  buttonText?: string;
  theme?: string;
}

export function NewsletterInline({
  title = 'メールで最新情報をお届け',
  description = '新着記事やお役立ち情報を配信中。',
  buttonText = '登録',
  theme = 'default',
}: NewsletterInlineProps) {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');

  const themeClasses: Record<string, { bg: string; border: string; text: string; btn: string; input: string }> = {
    default: { bg: 'bg-crimson-red/5', border: 'border-crimson-red/20', text: 'text-white', btn: 'bg-crimson-red text-white', input: 'border-soft-gray-border/30' },
    warm: { bg: 'bg-orange-50', border: 'border-orange-200', text: 'text-slate-800', btn: 'bg-orange-500 text-white', input: 'border-orange-200' },
    professional: { bg: 'bg-slate-800', border: 'border-slate-700', text: 'text-white', btn: 'bg-white text-slate-900', input: 'border-slate-600 bg-slate-700 text-white' },
    ocean: { bg: 'bg-blue-50', border: 'border-blue-200', text: 'text-slate-800', btn: 'bg-blue-500 text-white', input: 'border-blue-200' },
    forest: { bg: 'bg-emerald-50', border: 'border-emerald-200', text: 'text-slate-800', btn: 'bg-emerald-500 text-white', input: 'border-emerald-200' },
  };
  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-6">
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className={`${t.bg} border ${t.border} rounded-xl p-4 sm:p-5`}>
          <div className="flex flex-col sm:flex-row sm:items-center gap-4">
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <Send className={`w-4 h-4 ${theme === 'professional' ? 'text-blue-400' : 'text-crimson-red'} shrink-0`} />
                <h3 className={`font-bold text-sm ${t.text}`}>{title}</h3>
              </div>
              <p className={`text-xs ${theme === 'professional' ? 'text-slate-400' : 'text-text-light-gray'}`}>{description}</p>
            </div>

            {status === 'success' ? (
              <div className="flex items-center gap-1.5 text-emerald-600 text-sm font-medium shrink-0">
                <CheckCircle className="w-4 h-4" /> {message}
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="flex gap-2 shrink-0">
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="メールアドレス"
                  required
                  className={`px-3 py-2 rounded-lg border ${t.input} text-sm w-48 focus:outline-none focus:ring-1 focus:ring-brand-primary`}
                />
                <button
                  type="submit"
                  disabled={status === 'loading'}
                  className={`px-4 py-2 rounded-lg text-sm font-semibold ${t.btn} transition-colors disabled:opacity-50 flex items-center gap-1.5`}
                >
                  {status === 'loading' ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : buttonText}
                </button>
              </form>
            )}
          </div>

          {status === 'error' && (
            <div className="flex items-center gap-1.5 text-red-500 text-xs mt-2">
              <AlertCircle className="w-3.5 h-3.5" /> {message}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
