"use client";

import { useState } from "react";
import {
  CreditCard,
  AlertCircle,
  Loader2,
  Lock,
  ArrowRight,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import type { BillingPeriod, Currency, TierId } from "@/lib/types/pricing";
import { fetchWithCSRF } from "@/lib/csrf-client";
import PricingSelectionModal from "./PricingSelectionModal";
import {
  closeHostedCheckoutWindow,
  openHostedCheckoutWindow,
  redirectHostedCheckout,
} from "@/lib/payments/client-checkout";

interface SubscriptionDetails {
  tier?: string;
  status?: string;
  needsPayment?: boolean;
  billingPeriod?: string;
  currentPeriodEnd?: string;
  cancelAtPeriodEnd?: boolean;
}

interface PaymentRequiredOverlayProps {
  lang: Lang;
  subscriptionDetails: SubscriptionDetails;
  billingCurrency: string;
  onPaymentStart: () => void;
  onPendingPlanUpdated?: () => Promise<void> | void;
}

export default function PaymentRequiredOverlay({
  lang,
  subscriptionDetails,
  billingCurrency,
  onPaymentStart,
  onPendingPlanUpdated,
}: PaymentRequiredOverlayProps) {
  const isAr = lang === "ar";
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showPricingModal, setShowPricingModal] = useState(false);

  const t = {
    title: isAr ? "الدفع مطلوب" : "Payment Required",
    subtitle: isAr
      ? "يرجى إكمال عملية الدفع للوصول إلى لوحة التحكم"
      : "Please complete payment to access your dashboard",
    description: isAr
      ? "اشتراكك يتطلب الدفع لتفعيل جميع الميزات. أكمل الدفع الآن للوصول الكامل."
      : "Your subscription requires payment to activate all features. Complete payment now for full access.",
    payNow: isAr ? "ادفع الآن" : "Pay Now",
    processing: isAr ? "جارٍ المعالجة..." : "Processing...",
    securePayment: isAr ? "دفع آمن عبر Stripe" : "Secure payment via Stripe",
    tier: isAr ? "الخطة" : "Plan",
    billing: isAr ? "الفوترة" : "Billing",
    currency: isAr ? "العملة" : "Currency",
  };

  const getTierName = (tier: string | undefined) => {
    const tierNames: Record<string, { en: string; ar: string }> = {
      tier1: { en: "Starter", ar: "المبتدئ" },
      tier2: { en: "Professional", ar: "المحترف" },
      tier3: { en: "Business", ar: "الأعمال" },
      tier4: { en: "Enterprise", ar: "المؤسسي" },
      tier5: { en: "Ultimate", ar: "النهائي" },
    };
    return tierNames[tier || "tier1"]?.[isAr ? "ar" : "en"] || tier;
  };

  const getBillingLabel = (period: string | undefined) => {
    if (period === "yearly") {
      return isAr ? "سنوي" : "Yearly";
    }

    return isAr ? "شهري" : "Monthly";
  };

  const handleShowPricingModal = () => {
    setShowPricingModal(true);
  };

  const handleTierSelected = async (
    tierId: TierId,
    billingPeriod: BillingPeriod,
    currency: Currency,
  ) => {
    const checkoutWindow = openHostedCheckoutWindow();

    try {
      setLoading(true);
      setError(null);
      setShowPricingModal(false);

      const response = await fetchWithCSRF(
        "/api/subscriptions/create-checkout",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            tierId,
            billingPeriod,
            currency,
            language: lang,
          }),
        },
      );

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to create checkout session");
      }

      const redirectUrl = data.sessionUrl || data.url;
      if (redirectUrl) {
        await onPendingPlanUpdated?.();
        const openedInNewTab = redirectHostedCheckout(
          checkoutWindow,
          redirectUrl,
        );
        if (!openedInNewTab) {
          onPaymentStart();
        }
      } else {
        throw new Error("No checkout URL received");
      }
    } catch (err) {
      closeHostedCheckoutWindow(checkoutWindow);
      setError(err instanceof Error ? err.message : "Payment failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-md">
      <div className="relative bg-white rounded-3xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
        {/* Decorative gradient */}
        <div className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-amber-500 via-orange-500 to-red-500" />

        {/* Lock icon header */}
        <div className="pt-8 pb-4 flex justify-center">
          <div className="relative">
            <div className="w-20 h-20 rounded-full bg-gradient-to-br from-amber-100 to-orange-100 flex items-center justify-center">
              <Lock className="w-10 h-10 text-amber-600" />
            </div>
            <div className="absolute -bottom-1 -right-1 w-8 h-8 rounded-full bg-red-500 flex items-center justify-center shadow-lg">
              <AlertCircle className="w-5 h-5 text-white" />
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="px-8 pb-8 text-center">
          <h2 className="text-2xl font-bold text-slate-900 mb-2">{t.title}</h2>
          <p className="text-slate-600 mb-6">{t.subtitle}</p>

          {/* Plan info */}
          <div className="bg-slate-50 rounded-xl p-4 mb-6 text-left">
            <div className="flex justify-between items-center mb-2">
              <span className="text-sm text-slate-500">{t.tier}</span>
              <span className="font-semibold text-slate-900">
                {getTierName(subscriptionDetails.tier)}
              </span>
            </div>
            <div className="mb-2 flex justify-between items-center">
              <span className="text-sm text-slate-500">{t.billing}</span>
              <span className="font-semibold text-slate-900">
                {getBillingLabel(subscriptionDetails.billingPeriod)}
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-sm text-slate-500">{t.currency}</span>
              <span className="font-semibold text-slate-900">
                {billingCurrency}
              </span>
            </div>
          </div>

          <p className="text-sm text-slate-500 mb-6">{t.description}</p>

          {error && (
            <div className="flex items-center gap-2 text-red-600 text-sm bg-red-50 px-4 py-3 rounded-lg mb-4">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {/* Pay button */}
          <button
            onClick={handleShowPricingModal}
            disabled={loading}
            className="w-full flex items-center justify-center gap-3 px-6 py-4 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-xl font-semibold text-lg shadow-lg shadow-brand-green/30 hover:shadow-xl hover:shadow-brand-green/40 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                {t.processing}
              </>
            ) : (
              <>
                <CreditCard className="w-5 h-5" />
                {t.payNow}
                <ArrowRight className="w-5 h-5" />
              </>
            )}
          </button>

          {/* Security note */}
          <div className="mt-4 flex items-center justify-center gap-2 text-xs text-slate-400">
            <Lock className="w-3 h-3" />
            <span>{t.securePayment}</span>
          </div>
        </div>
      </div>

      {/* Pricing Selection Modal */}
      {showPricingModal && (
        <PricingSelectionModal
          lang={lang}
          isOpen={showPricingModal}
          onClose={() => setShowPricingModal(false)}
          onTierSelected={handleTierSelected}
          defaultTier={
            (subscriptionDetails.tier as TierId | undefined) ?? "tier2"
          }
          defaultCurrency={billingCurrency as Currency}
          defaultBillingPeriod={
            subscriptionDetails.billingPeriod === "yearly"
              ? "yearly"
              : "monthly"
          }
          isSubmitting={loading}
          required
        />
      )}
    </div>
  );
}
