'use client';

import React, { useState, useEffect, useCallback } from 'react';

export interface PopupModalProps {
  title?: string;
  description?: string;
  buttonText?: string;
  placeholder?: string;
  imageUrl?: string;
  delaySeconds?: number;
}

export const PopupModal = ({
  title = 'お得な情報をお届け！',
  description = 'ニュースレターに登録して、最新の攻略情報やアップデート情報をいち早く受け取りましょう。',
  buttonText = '登録する',
  placeholder = 'メールアドレス',
  imageUrl = 'https://images.unsplash.com/photo-1586339949916-3e9457bef6d3?q=80&w=2070&auto=format&fit=crop',
  delaySeconds = 3,
}: PopupModalProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const SESSION_KEY = 'popup_modal_shown';
  const isEditor = typeof window !== 'undefined' && window.location.pathname.startsWith('/page_editor_admin');

  useEffect(() => {
    // Never show the real popup in the editor
    if (isEditor) return;

    const hasShown = sessionStorage.getItem(SESSION_KEY);
    const isDev = process.env.NODE_ENV === 'development';

    // In dev, we bypass session storage for easier testing
    if (!isDev && hasShown) return;

    const timer = setTimeout(() => {
      setIsOpen(true);
      // Lock scroll
      document.body.style.overflow = 'hidden';
    }, delaySeconds * 1000);

    return () => {
      clearTimeout(timer);
      // Ensure scroll is unlocked if component unmounts
      document.body.style.overflow = '';
    };
  }, [delaySeconds, isEditor]);

  const handleClose = useCallback(() => {
    setIsOpen(false);
    document.body.style.overflow = '';
    if (!isEditor) {
      sessionStorage.setItem(SESSION_KEY, 'true');
    }
  }, [isEditor]);

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

    setLoading(true);
    setError(null);

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

      const data = await res.json();

      if (res.ok && data.success) {
        setSuccess(true);
        setTimeout(() => {
          handleClose();
        }, 2000);
      } else {
        setError(data.message || 'エラーが発生しました。');
      }
    } catch (err) {
      setError('通信エラーが発生しました。');
    } finally {
      setLoading(false);
    }
  };

  // Static preview for the editor
  if (isEditor) {
    return (
      <div className="bg-[#1A1A1F] border-2 border-dashed border-[#E60023]/40 p-6 rounded-xl flex items-center gap-4 my-4 opacity-90 hover:opacity-100 transition-all duration-300">
        <div className="w-12 h-12 bg-[#E60023]/10 rounded-full flex items-center justify-center text-[#E60023] text-2xl shadow-inner shadow-[#E60023]/5">
          🎁
        </div>
        <div>
          <h4 className="font-bold text-white">Popup Modal</h4>
          <p className="text-xs text-gray-400">
            Triggers after {delaySeconds}s delay on live site. Will NOT appear in editor.
          </p>
        </div>
      </div>
    );
  }

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[300000] flex items-center justify-center p-4">
      {/* Overlay */}
      <div 
        className="absolute inset-0 bg-black/60 backdrop-blur-sm" 
        onClick={handleClose}
      />

      {/* Modal Content */}
      <div className="relative z-[300001] bg-[#1A1A1F] border border-[#2A2A33] rounded-2xl overflow-hidden shadow-2xl max-w-2xl w-full flex flex-col md:flex-row animate-in fade-in zoom-in duration-300">
        {/* Left Side: Image */}
        <div className="md:w-1/2 h-48 md:h-auto overflow-hidden relative">
          <img 
            src={imageUrl} 
            alt="Promotion" 
            className="w-full h-full object-cover"
          />
          {/* Subtle gradient overlay on image */}
          <div className="absolute inset-0 bg-gradient-to-r from-transparent to-[#1A1A1F]/20 md:to-[#1A1A1F]/0" />
        </div>

        {/* Right Side: Content */}
        <div className="md:w-1/2 p-8 flex flex-col justify-center relative">
          <button 
            onClick={handleClose}
            className="absolute top-4 right-4 text-gray-500 hover:text-white transition-colors"
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>

          {success ? (
            <div className="text-center py-8 animate-in slide-in-from-bottom-4 duration-500">
              <div className="w-16 h-16 bg-[#E60023]/20 text-[#E60023] rounded-full flex items-center justify-center mx-auto mb-4 text-3xl">
                ✓
              </div>
              <h3 className="text-2xl font-bold text-white mb-2">ありがとうございます！</h3>
              <p className="text-gray-400">ニュースレターに正常に登録されました。</p>
            </div>
          ) : (
            <>
              <div className="mb-2">
                <span className="bg-[#E60023] text-white text-[10px] font-bold px-2 py-1 rounded uppercase tracking-wider">
                  Limited Offer
                </span>
              </div>
              <h3 className="text-2xl font-bold text-white mb-4 leading-tight">{title}</h3>
              <p className="text-gray-400 mb-6 text-sm leading-relaxed">
                {description}
              </p>

              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder={placeholder}
                    required
                    className="w-full px-4 py-3 rounded-lg bg-[#2A2A33] border border-[#3F3F4A] text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-[#E60023] focus:border-transparent transition-all"
                  />
                  {error && <p className="text-red-500 text-xs mt-1 font-medium">{error}</p>}
                </div>

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full bg-[#E60023] hover:bg-[#FF2A3D] text-white font-bold py-3 rounded-lg shadow-lg shadow-[#E60023]/20 transition-all transform active:scale-95 disabled:opacity-50 disabled:active:scale-100"
                >
                  {loading ? (
                    <span className="flex items-center justify-center gap-2">
                      <svg className="animate-spin h-5 w-5 text-white" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      送信中...
                    </span>
                  ) : (
                    buttonText
                  )}
                </button>
              </form>
              <p className="text-[10px] text-gray-500 mt-4 text-center">
                登録することで当サイトのプライバシーポリシーに同意したものとみなされます。
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
