"use client";

import { useEffect, useState, type ReactNode } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { Lock, Crown, LogIn, UserPlus } from "lucide-react";
import { usePaymentStatus } from "@/lib/usePaymentStatus";
import { formatPrice, FREE_BUNDLE_PRICE } from "@/lib/pricing";

const FREE_USE_LIMIT = 4;

type GateInfo = { slug: string; name: string; tier: "free" | "pro"; price?: number };

export default function ToolAccessGate({ tool, children }: { tool: GateInfo; children: ReactNode }) {
  const { data: session, status } = useSession();
  const { loading: accessLoading, plan, adFree, unlockedTools } = usePaymentStatus({
    kind: "TOOL",
    toolSlug: tool.slug,
  });
  const [checked, setChecked] = useState(false);
  const [limitReached, setLimitReached] = useState(false);

  const isLoggedIn = status === "authenticated";
  const isPro = plan === "PRO" || session?.user?.plan === "PRO";
  const toolUnlocked = isPro || unlockedTools.includes(tool.slug);
  const price = typeof tool.price === "number" ? tool.price : 5;

  useEffect(() => {
    if (status === "loading" || (isLoggedIn && accessLoading)) return;
    if (tool.tier === "pro" || isLoggedIn) {
      setChecked(true);
      return;
    }
    // Anonymous user on a free tool — track uses in localStorage.
    const key = `sth_usage_${tool.slug}`;
    const count = Number(localStorage.getItem(key) || "0");
    if (count >= FREE_USE_LIMIT) {
      setLimitReached(true);
    } else {
      localStorage.setItem(key, String(count + 1));
    }
    setChecked(true);
  }, [status, isLoggedIn, accessLoading, tool.slug, tool.tier]);

  if (!checked) {
    return <div className="h-40 animate-pulse rounded-2xl bg-heading/5" />;
  }

  // Pro tool, not unlocked (neither Pro plan nor bought individually)
  if (tool.tier === "pro" && !toolUnlocked) {
    return (
      <div className="relative overflow-hidden rounded-2xl">
        <div className="pointer-events-none select-none blur-sm">{children}</div>
        <div className="absolute inset-0 grid place-items-center bg-white/70 backdrop-blur-sm">
          <div className="mx-4 max-w-xs rounded-2xl border border-brand/20 bg-white p-6 text-center shadow-xl">
            <span className="mx-auto grid h-11 w-11 place-items-center rounded-full bg-brand-gradient text-white">
              <Crown size={18} />
            </span>
            <p className="mt-3 text-sm font-semibold text-heading">This is a Paid tool</p>
            <p className="mt-1 text-[13px] text-heading/60">
              Unlock {tool.name} for {formatPrice(price)}, or go Pro to unlock every tool.
            </p>
            <Link
              href={isLoggedIn ? `/upgrade/${tool.slug}` : `/signup?callbackUrl=/upgrade/${tool.slug}`}
              className="btn-glow mt-4 flex items-center justify-center gap-2 rounded-full bg-brand-gradient px-5 py-2.5 text-xs font-semibold text-white"
            >
              <Crown size={13} /> {isLoggedIn ? `Unlock for ${formatPrice(price)}` : "Sign Up To Unlock"}
            </Link>
          </div>
        </div>
      </div>
    );
  }

  // Free tool, anonymous/free user who hit the use limit (bypassed once ad-free is bought)
  if (limitReached && !adFree) {
    return (
      <div className="relative overflow-hidden rounded-2xl">
        <div className="pointer-events-none select-none blur-sm">{children}</div>
        <div className="absolute inset-0 grid place-items-center bg-white/70 backdrop-blur-sm">
          <div className="mx-4 max-w-xs rounded-2xl border border-brand/20 bg-white p-6 text-center shadow-xl">
            <span className="mx-auto grid h-11 w-11 place-items-center rounded-full bg-brand-gradient text-white">
              <Lock size={18} />
            </span>
            <p className="mt-3 text-sm font-semibold text-heading">Free limit reached</p>
            <p className="mt-1 text-[13px] text-heading/60">
              You&apos;ve used this tool {FREE_USE_LIMIT} times. Create a free account, or remove ads
              and limits on every free tool for {formatPrice(FREE_BUNDLE_PRICE)}.
            </p>
            <div className="mt-4 flex gap-2">
              <Link
                href="/signup"
                className="btn-glow flex flex-1 items-center justify-center gap-1.5 rounded-full bg-brand-gradient px-4 py-2.5 text-xs font-semibold text-white"
              >
                <UserPlus size={13} /> Sign Up
              </Link>
              <Link
                href="/login"
                className="flex flex-1 items-center justify-center gap-1.5 rounded-full bg-heading/5 px-4 py-2.5 text-xs font-semibold text-heading"
              >
                <LogIn size={13} /> Log In
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
