import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { CloseIcon } from './icons/CloseIcon';
import { SpinnerIcon } from './icons/SpinnerIcon';
import { apiUrl, logNonAbortError } from '../../lib/api';
import { useModalA11y } from '../../hooks/useModalA11y';

interface UpgradeModalProps {
  isLoggedIn: boolean;
  /** Why the modal opened: a plain filter-cap hit, or an attempt to add filters on
   *  a shared link. Only changes the wording. */
  reason?: 'filters' | 'shared';
  /** Anonymous only: log into an existing account. */
  onLoginClick: () => void;
  /** Anonymous only: create a free account (the preferred, no-cost next step). */
  onRegisterClick: () => void;
  /** Anonymous only: register and go straight to lifetime checkout. */
  onRegisterAndUpgrade: () => void;
  /** Logged-in only: start lifetime checkout for unlimited filters. */
  onStartCheckout: () => Promise<void>;
  /** Dismiss the modal and keep exploring with the current filter allowance. */
  onClose: () => void;
}

export default function UpgradeModal({
  isLoggedIn,
  reason = 'filters',
  onLoginClick,
  onRegisterClick,
  onRegisterAndUpgrade,
  onStartCheckout,
  onClose,
}: UpgradeModalProps) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pricePence, setPricePence] = useState<number | null>(null);
  const dialogRef = useModalA11y();

  useEffect(() => {
    fetch(apiUrl('pricing'))
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        if (data) setPricePence(data.current_price_pence);
      })
      .catch((err) => logNonAbortError('Failed to fetch pricing', err));
  }, []);

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

  const priceLabel =
    pricePence === null
      ? '...'
      : pricePence === 0
        ? t('upgrade.free')
        : `\u00A3${pricePence / 100}`;
  const isFree = pricePence === 0;

  // Registered users see the lifetime upsell directly; anonymous users are nudged to
  // create a free account first (more filters + save/share/export), with the paid
  // tier offered as the route to unlimited.
  // The `shared` reason only applies to anonymous visitors (lockFilterAdds is
  // anonymous-only), so logged-in users always get the plain lifetime-upsell copy.
  const title = isLoggedIn ? t('upgrade.title') : t('upgrade.titleRegister');
  const description = isLoggedIn
    ? t('upgrade.description')
    : reason === 'shared'
      ? t('upgrade.descriptionSharedRegister')
      : t('upgrade.descriptionRegister');

  const handleUpgrade = async () => {
    setLoading(true);
    setError(null);
    try {
      await onStartCheckout();
    } catch (err) {
      setError(err instanceof Error ? err.message : t('upgrade.checkoutFailed'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/50"
      role="presentation"
    >
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="upgrade-modal-title"
        tabIndex={-1}
        className="relative w-full max-w-md mx-4 bg-white dark:bg-warm-800 rounded-2xl shadow-2xl border border-warm-200 dark:border-warm-700 overflow-hidden outline-none"
      >
        {/* Close button */}
        <button
          type="button"
          onClick={onClose}
          aria-label={t('common.close')}
          className="absolute top-3 right-3 text-warm-400 hover:text-warm-700 dark:hover:text-warm-300"
        >
          <CloseIcon className="w-5 h-5" />
        </button>

        {/* Header */}
        <div className="bg-gradient-to-br from-navy-950 to-teal-900 px-6 py-8 text-center">
          <h2 id="upgrade-modal-title" className="text-2xl font-bold text-white mb-2">
            {title}
          </h2>
          <p className="text-warm-300 text-sm">{description}</p>
        </div>

        {/* Body */}
        <div className="px-6 py-6">
          {isLoggedIn ? (
            // Registered free user: pay to unlock unlimited filters.
            <>
              <div className="flex items-baseline justify-center gap-1 mb-4">
                <span className="text-4xl font-extrabold text-navy-950 dark:text-warm-100">
                  {priceLabel}
                </span>
                {!isFree && (
                  <span className="text-warm-500 dark:text-warm-400 text-lg">
                    {t('pricingPage.lifetime')}
                  </span>
                )}
              </div>
              <p className="text-center text-sm text-warm-500 dark:text-warm-400 mb-6">
                {isFree ? t('upgrade.freeForEarly') : t('upgrade.oneTimePayment')}
              </p>
              <button
                onClick={handleUpgrade}
                disabled={loading}
                className="w-full px-6 py-3 border border-[#d27a11] bg-[#f09a22] text-navy-950 rounded-lg font-semibold hover:bg-[#df8614] transition-colors text-lg shadow-lg shadow-[#7a3905]/25 disabled:opacity-50 disabled:cursor-wait flex items-center justify-center gap-2"
              >
                {loading && <SpinnerIcon className="w-5 h-5 animate-spin" />}
                {loading
                  ? t('upgrade.redirecting')
                  : isFree
                    ? t('upgrade.claimFreeAccess')
                    : t('upgrade.upgradeFor', { price: priceLabel })}
              </button>
            </>
          ) : (
            // Anonymous: create a free account first (more filters + save/share/export),
            // with the paid lifetime tier offered below as the route to unlimited.
            <>
              <button
                onClick={onRegisterClick}
                className="w-full px-6 py-3 border border-[#d27a11] bg-[#f09a22] text-navy-950 rounded-lg font-semibold hover:bg-[#df8614] transition-colors text-lg shadow-lg shadow-[#7a3905]/25"
              >
                {t('upgrade.registerFree')}
              </button>
              <button
                onClick={onLoginClick}
                className="w-full px-4 py-2 mt-2 text-sm text-teal-600 dark:text-teal-400 hover:text-teal-800 dark:hover:text-teal-300"
              >
                {t('upgrade.alreadyHaveAccount')}
              </button>
              <div className="mt-5 pt-4 border-t border-warm-200 dark:border-warm-700 text-center">
                <p className="text-sm text-warm-500 dark:text-warm-400 mb-2">
                  {t('upgrade.lifetimeUpsell')}
                </p>
                <button
                  onClick={onRegisterAndUpgrade}
                  className="text-sm font-semibold text-[#c8780f] hover:text-[#a86409] dark:text-[#f09a22] dark:hover:text-[#df8614]"
                >
                  {t('upgrade.goLifetime', { price: priceLabel })}
                </button>
              </div>
            </>
          )}

          {error && (
            <p className="mt-3 text-center text-sm text-red-600 dark:text-red-400">{error}</p>
          )}

          <button
            onClick={onClose}
            className="w-full mt-4 text-center text-sm text-warm-400 dark:text-warm-500 hover:text-warm-600 dark:hover:text-warm-400"
          >
            {t('upgrade.continueFree')}
          </button>
        </div>
      </div>
    </div>
  );
}
