"use client";

import React, { useState, useEffect } from "react";
import { useI18n } from "@/lib/i18n/context";
import { X, Sparkles } from "lucide-react";
import { FREE_SCAN_LIMIT } from "@/lib/limits";
import { getSessionQuota } from "@/lib/auth/sessionClient";
import { PricingPlans } from "./PricingPlans";

interface PaywallModalProps {
  isOpen: boolean;
  onClose: () => void;
  reason?: "scanLimit" | "exportLimit";
  initialPlan?: "weekly" | "annual" | "lifetime";
  onSuccessUpgrade?: () => void;
}

export function PaywallModal({
  isOpen,
  onClose,
  reason = "scanLimit",
  initialPlan = "annual",
  onSuccessUpgrade,
}: PaywallModalProps) {
  const { t, language } = useI18n();
  const isDe = language === "de";
  const [scanCount, setScanCount] = useState<number>(FREE_SCAN_LIMIT);
  const [freeAllowance, setFreeAllowance] = useState<number>(FREE_SCAN_LIMIT);
  const [launchBonus, setLaunchBonus] = useState<boolean>(false);
  const [bonusRemaining, setBonusRemainingState] = useState<number>(0);

  useEffect(() => {
    if (!isOpen) return;
    getSessionQuota().then((quota) => {
      setScanCount(quota.scanCount);
      setFreeAllowance(
        Number.isFinite(quota.scanLimit) ? quota.scanLimit : FREE_SCAN_LIMIT
      );
      setLaunchBonus(quota.launchBonus);
      setBonusRemainingState(
        quota.launchBonus ? Math.max(0, quota.scanLimit - quota.scanCount) : 0
      );
    });
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[95] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-fade-in font-sans">
      <div className="relative w-full max-w-3xl bg-white border-2 border-black">
        {/* Top Header Banner (Zenith Black Architecture) */}
        <div className="relative bg-black px-6 py-8 text-white text-center border-b border-black">
          <button
            onClick={onClose}
            className="absolute top-4 right-4 p-1.5 border border-white/20 hover:border-white text-white hover:bg-white/10 transition-colors"
            aria-label="Close"
          >
            <X className="h-4 w-4" />
          </button>

          <div className="inline-flex items-center gap-1.5 px-2.5 py-0.5 bg-white/10 border border-white/20 text-white font-mono text-[10px] uppercase tracking-caps mb-3">
            <Sparkles className="h-3 w-3 text-white" />
            <span>{isDe ? "SCANRECEIPTS PRO" : "SCANRECEIPTS PRO"}</span>
          </div>

          <h2 className="font-display text-2xl sm:text-3xl font-bold tracking-tight text-white">
            {t.paywall?.modalTitle || (isDe ? "Unbegrenzte Belege & Excel-Export" : "Unlimited Receipts & Excel Export")}
          </h2>
          <p className="mt-2 text-xs sm:text-sm text-[#94A3B8] max-w-md mx-auto font-sans">
            {reason === "scanLimit"
              ? (launchBonus
                  ? (isDe
                      ? (bonusRemaining > 0
                          ? `Monatliches Kontingent erreicht – noch ${bonusRemaining} Bonus-Scans übrig. ${t.paywall?.modalSubtitleBonus || "Upgrade für unbegrenzte Erfassung."}`
                          : `${t.paywall?.modalSubtitleBonus || "Willkommens-Bonus verbraucht: Jetzt 15 Gratis-Scans pro Monat. Upgrade für unbegrenzte Erfassung."}`)
                      : (bonusRemaining > 0
                          ? `Monthly allowance reached – ${bonusRemaining} bonus scans left. ${t.paywall?.modalSubtitleBonus || "Upgrade for unlimited ingestion."}`
                          : `${t.paywall?.modalSubtitleBonus || "Welcome bonus used: now 15 free scans per month. Upgrade for unlimited ingestion."}`))
                  : (isDe
                      ? `Kostenloses Kontingent erreicht (${scanCount} von ${freeAllowance} Gratis-Scans aufgebraucht). Upgrade für unbegrenzte Belegerfassung.`
                      : `Free scan limit reached (${scanCount} of ${freeAllowance} free scans used). Upgrade to Pro for unlimited receipt ingestion.`))
              : (t.paywall?.triggerReasons?.exportLimit ||
                  (isDe
                    ? "Pro-Funktion: Exportiere unbegrenzt Belege als Dual-Sheet Excel & CSV."
                    : "Pro Feature: Export unlimited receipts to Dual-Sheet Excel & CSV."))}
          </p>
        </div>

        <div className="p-6 sm:p-8">
          <PricingPlans initialPlan={initialPlan} onSuccessUpgrade={onSuccessUpgrade} onClose={onClose} />
        </div>
      </div>
    </div>
  );
}
