"use client";

import React, { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Sparkles, CheckCircle2 } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { apiFetch } from "@/lib/csrf/client";
import { PricingPlans } from "@/components/paywall/PricingPlans";

export default function PricingPage() {
  const { language } = useI18n();
  const isDe = language === "de";
  const router = useRouter();
  const [isPro, setIsPro] = useState(false);
  const [currentPlan, setCurrentPlan] = useState<string | null>(null);
  const [checked, setChecked] = useState(false);

  const fetchStatus = useCallback(async () => {
    try {
      const res = await apiFetch("/api/auth/session");
      if (res.ok) {
        const data = await res.json();
        const user = data?.user;
        setIsPro(Boolean(user?.isPro));
        setCurrentPlan(user?.plan || (user?.isPro ? "annual" : "free"));
      }
    } catch {
      // Guest / signed-out — treat as free tier.
    } finally {
      setChecked(true);
    }
  }, []);

  useEffect(() => {
    fetchStatus();
  }, [fetchStatus]);

  const handleDowngradeSuccess = () => {
    setIsPro(false);
    setCurrentPlan("free");
    fetchStatus();
  };

  return (
    <div className="space-y-8 font-sans max-w-5xl">
      {/* Header */}
      <div className="pb-6 border-b border-[#E2E8F0]">
        <div className="flex items-center gap-2 mb-1">
          <span className="w-2.5 h-2.5 bg-black"></span>
          <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
            {isDe ? "ABONNEMENT" : "SUBSCRIPTION"}
          </span>
        </div>
        <h1 className="font-display text-3xl sm:text-4xl font-bold tracking-tight text-black">
          {isDe ? "Preise & Pläne" : "Pricing & Plans"}
        </h1>
        <p className="text-xs text-[#64748B] font-mono mt-1">
          {isDe
            ? "Wähle jederzeit den Plan, der zu dir passt — oder verwalte dein aktives Abonnement."
            : "Pick the plan that fits you, any time — or manage your active subscription."}
        </p>
      </div>

      {checked && isPro && (
        <div className="p-4 bg-emerald-50 border border-emerald-300 flex items-center gap-3 font-mono text-xs text-emerald-950">
          <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0" />
          <div>
            <span className="font-bold">
              {isDe ? "Du hast derzeit eine aktive Pro-Lizenz." : "You currently have an active Pro license."}
            </span>{" "}
            <span className="text-emerald-800">
              {isDe
                ? "Dein aktueller Plan ist unten markiert. Du kannst den Plan wechseln oder jederzeit auf Free kündigen."
                : "Your active plan is marked below. You can switch plans or cancel to Free any time."}
            </span>
          </div>
        </div>
      )}

      <div className="bg-white border border-[#E2E8F0] p-6 sm:p-8">
        <div className="flex items-center gap-1.5 text-[#475569] font-mono text-[10px] uppercase tracking-caps mb-5">
          <Sparkles className="h-3 w-3" />
          <span>{isDe ? "SCANRECEIPTS PRO" : "SCANRECEIPTS PRO"}</span>
        </div>
        <PricingPlans
          currentPlan={currentPlan}
          isPro={isPro}
          onSuccessUpgrade={() => {
            fetchStatus();
            router.push("/dashboard");
          }}
          onDowngrade={handleDowngradeSuccess}
        />
      </div>
    </div>
  );
}
