"use client";

import React, { useState } from "react";
import Link from "next/link";
import { useI18n } from "@/lib/i18n/context";
import { Check, ShieldCheck, Zap, ArrowRight, AlertTriangle, CheckCircle2, RotateCcw, AlertCircle } from "lucide-react";
import { apiFetch } from "@/lib/csrf/client";

export interface PricingPlansProps {
  initialPlan?: "weekly" | "annual" | "lifetime";
  currentPlan?: string | null;
  isPro?: boolean;
  onSuccessUpgrade?: () => void;
  /** Called after a successful mock unlock and on legal-link clicks — lets an embedding modal dismiss itself. Omit on a standalone page. */
  onClose?: () => void;
  /** Called when subscription is downgraded/cancelled */
  onDowngrade?: () => void;
}

/**
 * The 3 plan cards, included-features list, and checkout/downgrade CTAs — shared between
 * PaywallModal (limit-reached popup) and /dashboard/pricing (the page reached
 * by proactively browsing plans, not by hitting a quota).
 */
export function PricingPlans({
  initialPlan = "annual",
  currentPlan,
  isPro = false,
  onSuccessUpgrade,
  onClose,
  onDowngrade,
}: PricingPlansProps) {
  const { t, language } = useI18n();
  const isDe = language === "de";
  const [selectedPlan, setSelectedPlan] = useState<"weekly" | "annual" | "lifetime">(initialPlan);
  const [isLoading, setIsLoading] = useState(false);
  const [checkoutError, setCheckoutError] = useState<string | null>(null);

  // Downgrade state
  const [isDowngrading, setIsDowngrading] = useState(false);
  const [showDowngradeConfirm, setShowDowngradeConfirm] = useState(false);
  const [downgradeError, setDowngradeError] = useState<string | null>(null);
  const [downgradeSuccess, setDowngradeSuccess] = useState(false);

  const isCurrentPlanActive = isPro && currentPlan === selectedPlan;

  const handleCheckout = async () => {
    if (isCurrentPlanActive) {
      return;
    }

    setIsLoading(true);
    setCheckoutError(null);
    try {
      const res = await apiFetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan: selectedPlan }),
      });
      const data = await res.json();
      if (data.mock && res.ok) {
        // Mock unlock for development & demonstration
        onSuccessUpgrade?.();
        alert(isDe ? "🎉 Pro-Lizenz erfolgreich freigeschaltet (Demo-Modus)!" : "🎉 Pro license unlocked successfully (Demo Mode)!");
        onClose?.();
        return;
      }
      if (data.url) {
        window.location.href = data.url;
        return;
      }
      if (!res.ok) {
        setCheckoutError(
          data?.error ||
            (isDe
              ? "Checkout-Session konnte nicht erstellt werden. Bitte erneut versuchen."
              : "Could not create the checkout session. Please try again.")
        );
      }
    } catch (err) {
      console.error(err);
      setCheckoutError(
        isDe
          ? "Verbindung zum Checkout-Server fehlgeschlagen. Bitte erneut versuchen."
          : "Connection to the checkout server failed. Please try again."
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleDowngrade = async () => {
    setIsDowngrading(true);
    setDowngradeError(null);
    try {
      const res = await apiFetch("/api/subscription/cancel", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
      });
      const data = await res.json();
      if (res.ok) {
        setDowngradeSuccess(true);
        setShowDowngradeConfirm(false);
        onDowngrade?.();
      } else {
        setDowngradeError(
          data?.error ||
            (isDe
              ? "Abonnement konnte nicht gekündigt werden. Bitte versuche es erneut."
              : "Could not cancel subscription. Please try again.")
        );
      }
    } catch (err) {
      console.error(err);
      setDowngradeError(
        isDe
          ? "Netzwerkfehler beim Kündigen des Abonnements."
          : "Network error while cancelling subscription."
      );
    } finally {
      setIsDowngrading(false);
    }
  };

  return (
    <div className="space-y-6">
      {downgradeSuccess && (
        <div className="p-4 bg-emerald-50 border border-emerald-300 font-mono text-xs text-emerald-900 flex items-center justify-between gap-3">
          <div className="flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
            <span>
              {isDe
                ? "Dein Abonnement wurde erfolgreich gekündigt. Dein Konto ist jetzt auf dem kostenlosen Free-Plan."
                : "Your subscription was successfully cancelled. Your account is now on the Free tier."}
            </span>
          </div>
        </div>
      )}

      {downgradeError && (
        <div className="p-3.5 bg-red-50 border border-red-300 font-mono text-xs text-red-900 flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
          <span>{downgradeError}</span>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* 1. Weekly Plan */}
        {(() => {
          const isThisPlanActive = isPro && currentPlan === "weekly";
          const isSelected = selectedPlan === "weekly";
          return (
            <div
              onClick={() => setSelectedPlan("weekly")}
              className={`cursor-pointer relative p-5 border transition-all ${
                isThisPlanActive
                  ? "border-2 border-emerald-600 bg-emerald-50/40 shadow-xs"
                  : isSelected
                  ? "border-2 border-black bg-[#EEF4FC]"
                  : "border-[#E2E8F0] hover:border-black bg-white"
              }`}
            >
              {isThisPlanActive && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-emerald-600 text-white border border-emerald-700 px-2.5 py-0.5 font-mono text-[9px] font-bold uppercase tracking-widest flex items-center gap-1 shadow-xs">
                  <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse"></span>
                  <span>{isDe ? "DU BIST HIER" : "YOU ARE HERE"}</span>
                </div>
              )}
              <span className="font-mono text-[10px] font-bold uppercase tracking-caps text-[#64748B] block mb-1">
                {t.pricing?.weeklyBadge || (isDe ? "WOCHEN-PASS" : "WEEKLY PASS")}
              </span>
              <h4 className="font-display text-base font-bold text-black">
                {t.pricing?.weeklyTitle || (isDe ? "7-Tage Pass" : "7-Day Pass")}
              </h4>
              <div className="mt-2 flex items-baseline gap-1">
                <span className="font-display text-2xl font-bold text-black">4,99 €</span>
                <span className="font-mono text-xs text-[#64748B]">{isDe ? "/ Wo." : "/ wk"}</span>
              </div>
              <p className="mt-2 font-sans text-[11px] text-[#475569]">
                {isDe ? "Inkl. 3 Tage kostenlos testen." : "Includes 3-day free trial."}
              </p>
              {isThisPlanActive && (
                <div className="mt-3 inline-flex items-center gap-1.5 text-[10px] font-mono text-emerald-800 font-bold uppercase">
                  <Check className="w-3 h-3 text-emerald-600" />
                  <span>{isDe ? "Aktiver Plan" : "Active Plan"}</span>
                </div>
              )}
            </div>
          );
        })()}

        {/* 2. Annual Plan (Highlight) */}
        {(() => {
          const isThisPlanActive = isPro && currentPlan === "annual";
          const isSelected = selectedPlan === "annual";
          return (
            <div
              onClick={() => setSelectedPlan("annual")}
              className={`cursor-pointer relative p-5 border transition-all ${
                isThisPlanActive
                  ? "border-2 border-emerald-600 bg-emerald-50/40 shadow-xs"
                  : isSelected
                  ? "border-2 border-black bg-[#EEF4FC]"
                  : "border-[#E2E8F0] hover:border-black bg-white"
              }`}
            >
              {isThisPlanActive ? (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-emerald-600 text-white border border-emerald-700 px-2.5 py-0.5 font-mono text-[9px] font-bold uppercase tracking-widest flex items-center gap-1 shadow-xs">
                  <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse"></span>
                  <span>{isDe ? "DU BIST HIER" : "YOU ARE HERE"}</span>
                </div>
              ) : (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-black text-white border border-black px-2 py-0.5 font-mono text-[9px] font-bold uppercase tracking-widest">
                  {isDe ? "BESTER WERT (-70%)" : "BEST VALUE (-70%)"}
                </div>
              )}
              <span className="font-mono text-[10px] font-bold uppercase tracking-caps text-black block mb-1">
                {isDe ? "EMPFOHLEN" : "RECOMMENDED"}
              </span>
              <h4 className="font-display text-base font-bold text-black">
                {t.pricing?.annualTitle || (isDe ? "Jahres-Lizenz" : "Annual License")}
              </h4>
              <div className="mt-2 flex items-baseline gap-1">
                <span className="font-display text-2xl font-bold text-black">39,99 €</span>
                <span className="font-mono text-xs text-[#64748B]">{isDe ? "/ Jahr" : "/ yr"}</span>
              </div>
              <p className="mt-2 font-sans text-[11px] text-[#475569] font-medium">
                {isDe ? "Nur ca. 3,33 €/Monat." : "Just ~$3.33/month."}
              </p>
              {isThisPlanActive && (
                <div className="mt-3 inline-flex items-center gap-1.5 text-[10px] font-mono text-emerald-800 font-bold uppercase">
                  <Check className="w-3 h-3 text-emerald-600" />
                  <span>{isDe ? "Aktiver Plan" : "Active Plan"}</span>
                </div>
              )}
            </div>
          );
        })()}

        {/* 3. Lifetime Plan */}
        {(() => {
          const isThisPlanActive = isPro && currentPlan === "lifetime";
          const isSelected = selectedPlan === "lifetime";
          return (
            <div
              onClick={() => setSelectedPlan("lifetime")}
              className={`cursor-pointer relative p-5 border transition-all ${
                isThisPlanActive
                  ? "border-2 border-emerald-600 bg-emerald-50/40 shadow-xs"
                  : isSelected
                  ? "border-2 border-black bg-[#EEF4FC]"
                  : "border-[#E2E8F0] hover:border-black bg-white"
              }`}
            >
              {isThisPlanActive && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-emerald-600 text-white border border-emerald-700 px-2.5 py-0.5 font-mono text-[9px] font-bold uppercase tracking-widest flex items-center gap-1 shadow-xs">
                  <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse"></span>
                  <span>{isDe ? "DU BIST HIER" : "YOU ARE HERE"}</span>
                </div>
              )}
              <span className="font-mono text-[10px] font-bold uppercase tracking-caps text-[#64748B] block mb-1">
                {t.pricing?.lifetimeBadge || (isDe ? "LIFETIME" : "LIFETIME")}
              </span>
              <h4 className="font-display text-base font-bold text-black">
                {t.pricing?.lifetimeTitle || (isDe ? "Lebenslang" : "Lifetime")}
              </h4>
              <div className="mt-2 flex items-baseline gap-1">
                <span className="font-display text-2xl font-bold text-black">{isDe ? "59,99 €" : "$59.99"}</span>
                <span className="font-mono text-xs text-[#64748B]">{isDe ? "einmalig" : "one-time"}</span>
              </div>
              <p className="mt-2 font-sans text-[11px] text-[#475569]">
                {isDe ? "Einmal zahlen, für immer nutzen." : "Pay once, use forever."}
              </p>
              {isThisPlanActive && (
                <div className="mt-3 inline-flex items-center gap-1.5 text-[10px] font-mono text-emerald-800 font-bold uppercase">
                  <Check className="w-3 h-3 text-emerald-600" />
                  <span>{isDe ? "Aktiver Plan" : "Active Plan"}</span>
                </div>
              )}
            </div>
          );
        })()}
      </div>

      {/* Included Features List */}
      <div className="bg-[#F8FAFC] p-4 border border-[#E2E8F0]">
        <h5 className="font-mono text-xs font-bold uppercase tracking-caps text-black mb-2">
          {isDe ? "In jedem Pro-Paket enthalten:" : "Included in every Pro license:"}
        </h5>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 font-mono text-xs text-[#475569]">
          <div className="flex items-center gap-2">
            <Check className="h-3.5 w-3.5 text-black shrink-0" />
            <span>{isDe ? "Unbegrenzte Beleg- & Rechnungs-Scans" : "Unlimited receipt & invoice scans"}</span>
          </div>
          <div className="flex items-center gap-2">
            <Check className="h-3.5 w-3.5 text-black shrink-0" />
            <span>{isDe ? "Bulk-Upload (Massen-Upload per Drag & Drop)" : "Bulk upload (drop 50+ files at once)"}</span>
          </div>
          <div className="flex items-center gap-2">
            <Check className="h-3.5 w-3.5 text-black shrink-0" />
            <span>{isDe ? "Unbegrenztes Langzeit-Cloud-Archiv" : "Unlimited long-term cloud archive"}</span>
          </div>
          <div className="flex items-center gap-2">
            <Check className="h-3.5 w-3.5 text-black shrink-0" />
            <span>{isDe ? "Alle KI- & Export-Funktionen inklusive" : "All AI & Export features included"}</span>
          </div>
        </div>
      </div>

      {/* Checkout CTA */}
      <div className="flex flex-col items-center">
        <button
          onClick={handleCheckout}
          disabled={isLoading || isCurrentPlanActive}
          className={`w-full sm:w-auto min-w-[280px] inline-flex items-center justify-center gap-2 px-8 py-3.5 font-mono text-xs uppercase tracking-caps transition-colors font-bold ${
            isCurrentPlanActive
              ? "bg-emerald-700 text-white cursor-default opacity-90"
              : "bg-black text-white hover:bg-[#334155] disabled:opacity-50"
          }`}
        >
          {isCurrentPlanActive ? (
            <>
              <CheckCircle2 className="h-4 w-4 text-emerald-300" />
              <span>{isDe ? "Aktueller Plan (Aktiv)" : "Current Plan (Active)"}</span>
            </>
          ) : (
            <>
              <Zap className="h-4 w-4" />
              <span>
                {isPro
                  ? isDe
                    ? `Zu ${selectedPlan === "weekly" ? "Wochen-Pass" : selectedPlan === "annual" ? "Jahres-Pro" : "Lifetime"} wechseln`
                    : `Switch to ${selectedPlan === "weekly" ? "Weekly Pass" : selectedPlan === "annual" ? "Annual Pro" : "Lifetime"}`
                  : selectedPlan === "weekly"
                  ? (isDe ? "3 Tage kostenlos testen" : "Start 3-Day Free Trial")
                  : selectedPlan === "annual"
                  ? (isDe ? "Jetzt Jahres-Pro aktivieren (39,99 €)" : "Activate Annual Pro ($39.99)")
                  : (isDe ? "Lifetime Lizenz sichern (59,99 €)" : "Get Lifetime License ($59.99)")}
              </span>
              <ArrowRight className="h-4 w-4" />
            </>
          )}
        </button>

        {checkoutError && (
          <p className="mt-3 w-full sm:w-auto inline-flex items-center justify-center gap-1.5 font-mono text-xs text-red-700 bg-red-50 border border-red-200 px-3 py-2">
            <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
            <span>{checkoutError}</span>
          </p>
        )}

        <p className="mt-3 font-mono text-[11px] text-[#64748B] flex items-center gap-1.5">
          <ShieldCheck className="h-3.5 w-3.5 text-black" />
          <span>{isDe ? "Sichere 256-Bit SSL-Verschlüsselung via Stripe" : "Secure 256-bit SSL encryption via Stripe"}</span>
        </p>

        <p className="mt-3 text-center font-mono text-[11px] text-[#64748B]">
          <span>{isDe ? "Mit dem Kauf akzeptieren Sie unsere " : "By purchasing you agree to our "}</span>
          <Link href="/terms" className="underline hover:text-black transition-colors" onClick={onClose}>
            {isDe ? "AGB" : "Terms"}
          </Link>
          <span>{isDe ? " und die " : " and "}</span>
          <Link href="/privacy" className="underline hover:text-black transition-colors" onClick={onClose}>
            {isDe ? "Datenschutzerklärung" : "Privacy Policy"}
          </Link>
          <span>.</span>
        </p>
      </div>

      {/* Downgrade to Free / Cancel Subscription Option */}
      {isPro && (
        <div className="pt-6 border-t border-[#E2E8F0] flex flex-col items-center text-center space-y-3">
          <div className="p-4 bg-[#F8FAFC] border border-[#E2E8F0] max-w-xl w-full flex flex-col sm:flex-row items-center justify-between gap-4 font-mono text-xs">
            <div className="text-left min-w-0">
              <span className="font-semibold text-black block">
                {isDe ? "Abonnement beenden & zu Free wechseln" : "Cancel Subscription & Downgrade to Free"}
              </span>
              <span className="text-[11px] text-[#64748B] block mt-0.5">
                {isDe
                  ? "Du kannst dein Abo jederzeit kündigen und das Monatskontingent von 15 Gratis-Scans nutzen."
                  : "You can cancel any time and continue using the 15 free scans monthly allowance."}
              </span>
            </div>
            {!showDowngradeConfirm ? (
              <button
                type="button"
                onClick={() => setShowDowngradeConfirm(true)}
                className="px-3.5 py-2 bg-white border border-red-300 text-red-700 hover:bg-red-50 font-mono text-xs uppercase tracking-caps font-semibold shrink-0 transition-colors"
              >
                {isDe ? "Auf Free downgraden" : "Downgrade to Free"}
              </button>
            ) : (
              <div className="flex items-center gap-2 shrink-0">
                <button
                  type="button"
                  onClick={() => setShowDowngradeConfirm(false)}
                  disabled={isDowngrading}
                  className="px-3 py-1.5 bg-white border border-[#E2E8F0] text-[#475569] hover:text-black font-mono text-xs uppercase"
                >
                  {isDe ? "Abbrechen" : "Keep Plan"}
                </button>
                <button
                  type="button"
                  onClick={handleDowngrade}
                  disabled={isDowngrading}
                  className="px-3.5 py-1.5 bg-red-600 hover:bg-red-700 text-white font-mono text-xs uppercase tracking-caps font-bold transition-colors disabled:opacity-50"
                >
                  {isDowngrading
                    ? isDe
                      ? "Wird gekündigt..."
                      : "Cancelling..."
                    : isDe
                    ? "Ja, kündigen"
                    : "Confirm Cancel"}
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
