import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { SpinnerIcon } from './icons/SpinnerIcon';
import { useModalA11y } from '../../hooks/useModalA11y';

interface LicenseSuccessModalProps {
  onClose: () => void;
  status?: 'verifying' | 'success' | 'delayed';
}

export default function LicenseSuccessModal({
  onClose,
  status = 'success',
}: LicenseSuccessModalProps) {
  const { t } = useTranslation();
  const isSuccess = status === 'success';
  const isVerifying = status === 'verifying';
  const dialogRef = useModalA11y();
  const particles = useMemo(
    () =>
      Array.from({ length: 40 }, (_, i) => ({
        id: i,
        left: Math.random() * 100,
        delay: Math.random() * 2,
        duration: 2 + Math.random() * 2,
        color: ['#10b981', '#06b6d4', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899'][
          Math.floor(Math.random() * 6)
        ],
        size: 6 + Math.random() * 6,
        isCircle: Math.random() > 0.5,
      })),
    []
  );

  useEffect(() => {
    if (!isSuccess) return;
    const timer = setTimeout(onClose, 8000);
    return () => clearTimeout(timer);
  }, [isSuccess, onClose]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);

  const title =
    status === 'verifying'
      ? t('licenseSuccess.verifyingTitle')
      : status === 'delayed'
        ? t('licenseSuccess.activationDelayedTitle')
        : t('licenseSuccess.title');
  const subtitle =
    status === 'verifying'
      ? t('licenseSuccess.verifyingSubtitle')
      : status === 'delayed'
        ? t('licenseSuccess.activationDelayedSubtitle')
        : t('licenseSuccess.subtitle');
  const description =
    status === 'verifying'
      ? t('licenseSuccess.verifyingDescription')
      : status === 'delayed'
        ? t('licenseSuccess.activationDelayedDescription')
        : t('licenseSuccess.description');

  return (
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/50"
      role="presentation"
    >
      {isSuccess && (
        <div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
          {particles.map((p) => (
            <div
              key={p.id}
              className="absolute animate-confetti"
              style={{
                left: `${p.left}%`,
                top: '-10px',
                width: `${p.size}px`,
                height: `${p.size}px`,
                backgroundColor: p.color,
                borderRadius: p.isCircle ? '50%' : '2px',
                animationDelay: `${p.delay}s`,
                animationDuration: `${p.duration}s`,
              }}
            />
          ))}
        </div>
      )}

      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="license-success-modal-title"
        tabIndex={-1}
        className="relative z-10 w-full max-w-sm mx-4 bg-white dark:bg-warm-800 rounded-2xl shadow-2xl border border-warm-200 dark:border-warm-700 text-center overflow-hidden outline-none"
      >
        <div className="bg-gradient-to-br from-navy-950 to-teal-900 px-6 py-8">
          <div className="h-14 mb-3 flex items-center justify-center">
            {isVerifying ? (
              <SpinnerIcon className="w-10 h-10 animate-spin text-teal-300" />
            ) : (
              <div className="text-5xl">{isSuccess ? '🎉' : '✓'}</div>
            )}
          </div>
          <h2 id="license-success-modal-title" className="text-2xl font-bold text-white">
            {title}
          </h2>
          <p className="text-warm-300 text-sm mt-2">{subtitle}</p>
        </div>
        <div className="px-6 py-6">
          <p className="text-warm-600 dark:text-warm-300 text-sm mb-6">{description}</p>
          {!isVerifying && (
            <button
              onClick={onClose}
              className="w-full px-6 py-3 bg-teal-600 text-white rounded-lg font-semibold hover:bg-teal-700 transition-colors text-lg"
            >
              {isSuccess ? t('licenseSuccess.startExploring') : t('licenseSuccess.stayOnPricing')}
            </button>
          )}
        </div>
      </div>

      <style>{`
        @keyframes confetti-fall {
          0% {
            transform: translateY(0) rotate(0deg);
            opacity: 1;
          }
          100% {
            transform: translateY(100vh) rotate(720deg);
            opacity: 0;
          }
        }
        .animate-confetti {
          animation: confetti-fall linear forwards;
        }
      `}</style>
    </div>
  );
}
