'use client';

import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Loader2, Mail, Sparkles } from 'lucide-react';
import Link from 'next/link';

/**
 * NewsletterSection Component - Modern Redesign
 * 
 * Newsletter subscription section for the homepage with enhanced visual design.
 * Allows users to subscribe to receive latest strategy guide updates.
 * 
 * Features:
 * - Dark gradient background with subtle pattern
 * - Section header with vertical red accent bar (consistent with other sections)
 * - Card container with border and shadow effects
 * - Enhanced input field with icon and better focus states
 * - Prominent subscribe button with hover glow effect
 * - Decorative sparkle elements
 * - Success/error notifications with animations
 * - Privacy policy link
 * - Loading state with spinner
 * - Fully responsive design (mobile/desktop)
 * - Accessibility compliant
 */
export function NewsletterSection({
  title,
  description,
  buttonText,
  placeholder,
}: {
  title?: string;
  description?: string;
  buttonText?: string;
  placeholder?: string;
} = {}) {
  const headingText = title || '最新攻略情報をメールで受け取る';
  const descText = description || '新しい攻略記事やイベント情報を週1回お届けします。\n最新のゲーム情報をいち早くキャッチしましょう！';
  const btnText = buttonText || '登録する';
  const placeholderText = placeholder || 'メールアドレスを入力';

  const [email, setEmail] = React.useState('');
  const [isLoading, setIsLoading] = React.useState(false);
  const [message, setMessage] = React.useState<{
    type: 'success' | 'error';
    text: string;
  } | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Clear previous messages
    setMessage(null);
    
    // Basic email validation
    if (!email || !email.includes('@')) {
      setMessage({
        type: 'error',
        text: '有効なメールアドレスを入力してください。'
      });
      return;
    }

    setIsLoading(true);

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

      const data = await response.json();

      if (response.ok) {
        setMessage({
          type: 'success',
          text: 'ご登録ありがとうございます！'
        });
        setEmail(''); // Clear the input on success
      } else {
        setMessage({
          type: 'error',
          text: data.message || 'エラーが発生しました。もう一度お試しください。'
        });
      }
    } catch (error) {
      setMessage({
        type: 'error',
        text: 'エラーが発生しました。もう一度お試しください。'
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <section className="relative py-16 md:py-20 bg-gradient-to-b from-[#0F0F12] via-[#1A1A1F] to-[#0F0F12] overflow-hidden">
      {/* Subtle background pattern */}
      <div className="absolute inset-0 opacity-5">
        <div className="absolute inset-0" style={{
          backgroundImage: 'radial-gradient(circle at 2px 2px, #E60023 1px, transparent 0)',
          backgroundSize: '40px 40px'
        }} />
      </div>

      <div className="container relative">
        {/* Section header with red accent bar */}
        <div className="flex items-center gap-3 mb-6 justify-center">
          <div className="w-1 h-8 bg-[#E60023] rounded-full" />
          <h2 className="text-3xl md:text-4xl font-bold text-white">
            {headingText}
          </h2>
          <div className="w-1 h-8 bg-[#E60023] rounded-full" />
        </div>

        {/* Description */}
        <p className="text-center text-base md:text-lg text-[#B8B8C0] mb-10 max-w-2xl mx-auto leading-relaxed">
          {descText}
        </p>

        {/* Card container */}
        <div className="max-w-3xl mx-auto">
          <div className="relative bg-[#202026] rounded-xl border border-[#2A2A33] p-6 md:p-8 shadow-xl hover:border-[#E60023]/50 transition-all duration-300">
            {/* Decorative sparkles */}
            <div className="absolute -top-3 -right-3 text-[#E60023] animate-pulse">
              <Sparkles className="w-6 h-6" />
            </div>
            <div className="absolute -bottom-3 -left-3 text-[#E60023] animate-pulse" style={{ animationDelay: '1s' }}>
              <Sparkles className="w-6 h-6" />
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-5">
              <div className="flex flex-col sm:flex-row gap-4">
                {/* Email Input with icon */}
                <div className="relative flex-1">
                  <div className="absolute left-4 top-1/2 -translate-y-1/2 text-[#B8B8C0] pointer-events-none">
                    <Mail className="w-5 h-5" />
                  </div>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder={placeholderText}
                    disabled={isLoading}
                    className="w-full h-14 pl-12 pr-4 rounded-xl border-2 border-[#2A2A33] bg-[#1A1A1F] text-white placeholder:text-[#B8B8C0] focus:outline-none focus:border-[#E60023] focus:shadow-[0_0_20px_rgba(230,0,35,0.3)] transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-base"
                    aria-label="メールアドレス"
                  />
                </div>
                
                {/* Submit Button with enhanced styling */}
                <Button
                  type="submit"
                  size="lg"
                  disabled={isLoading}
                  className="h-14 bg-[#E60023] hover:bg-[#FF2A3D] text-white font-bold px-10 rounded-xl shadow-lg hover:shadow-[0_0_25px_rgba(230,0,35,0.5)] transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-base whitespace-nowrap"
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="h-5 w-5 animate-spin mr-2" />
                      送信中...
                    </>
                  ) : (
                    btnText
                  )}
                </Button>
              </div>

              {/* Success/Error Messages with animation */}
              {message && (
                <div
                  className={`p-4 rounded-xl text-sm font-medium animate-in fade-in slide-in-from-top-2 duration-300 ${
                    message.type === 'success'
                      ? 'bg-[#E60023]/20 text-white border border-[#E60023]/40 shadow-[0_0_15px_rgba(230,0,35,0.2)]'
                      : 'bg-[#FF2A3D]/20 text-white border border-[#FF2A3D]/40 shadow-[0_0_15px_rgba(255,42,61,0.2)]'
                  }`}
                  role="alert"
                >
                  {message.text}
                </div>
              )}

            </form>
          </div>
        </div>
      </div>
    </section>
  );
}
