"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";

const POPULAR_PACKAGES = [
  { id: "credits_250", credits: 250, price: "€50.00" },
  { id: "credits_500", credits: 500, price: "€90.00", savings: 10 },
  { id: "credits_1000", credits: 1000, price: "€170.00", savings: 15 },
];

interface LowBalancePopupProps {
  threshold?: number;
}

export function LowBalancePopup({ threshold = 50 }: LowBalancePopupProps) {
  const { data: session } = useSession();
  const [balance, setBalance] = useState<number | null>(null);
  const [visible, setVisible] = useState(false);
  const [dismissed, setDismissed] = useState(false);

  const fetchBalance = useCallback(async () => {
    try {
      const res = await fetch("/api/credits/balance");
      if (res.ok) {
        const data = await res.json();
        setBalance(data.credits ?? 0);
      }
    } catch {
      // silently fail
    }
  }, []);

  useEffect(() => {
    if (!session?.user) return;

    // Check if already dismissed this session
    if (sessionStorage.getItem("low-balance-dismissed") === "true") {
      setDismissed(true);
      return;
    }

    fetchBalance();
  }, [session, fetchBalance]);

  useEffect(() => {
    if (balance === null || balance >= threshold || dismissed) return;

    const timer = setTimeout(() => {
      setVisible(true);
    }, 3000);

    return () => clearTimeout(timer);
  }, [balance, threshold, dismissed]);

  const handleDismiss = () => {
    setVisible(false);
    setDismissed(true);
    sessionStorage.setItem("low-balance-dismissed", "true");
  };

  if (!visible || dismissed) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={handleDismiss}
      />

      {/* Modal */}
      <div className="relative bg-[#111127] border border-gold/30 rounded-2xl shadow-2xl shadow-gold/10 max-w-md w-full p-6 animate-in fade-in zoom-in-95 duration-300">
        {/* Close button */}
        <button
          onClick={handleDismiss}
          className="absolute top-3 right-3 text-text-muted hover:text-white transition-colors p-1"
          aria-label="Close"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        {/* Icon */}
        <div className="flex justify-center mb-4">
          <div className="w-14 h-14 rounded-full bg-gold/10 border border-gold/30 flex items-center justify-center">
            <svg className="w-7 h-7 text-gold" viewBox="0 0 24 24" fill="currentColor">
              <circle cx="12" cy="12" r="10" fill="currentColor" opacity="0.2" />
              <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" fill="none" />
              <text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="bold" fill="currentColor">C</text>
            </svg>
          </div>
        </div>

        {/* Heading */}
        <h2 className="text-xl font-bold text-white text-center mb-1">
          Running low on credits!
        </h2>

        {/* Balance */}
        <p className="text-center mb-1">
          <span className="text-text-muted text-sm">Current balance: </span>
          <span className="text-gold font-bold text-lg">{balance?.toLocaleString()}</span>
          <span className="text-text-muted text-sm"> credits</span>
        </p>

        {/* Subtext */}
        <p className="text-center text-gold/80 text-sm mb-5">
          Top up now and save up to 20%!
        </p>

        {/* Quick-buy packages */}
        <div className="grid grid-cols-3 gap-3 mb-5">
          {POPULAR_PACKAGES.map((pkg) => (
            <Link
              key={pkg.id}
              href={`/credits/buy`}
              className="group relative bg-surface border border-white/10 hover:border-gold/50 rounded-xl p-3 text-center transition-all hover:bg-surface-light"
            >
              {pkg.savings ? (
                <span className="absolute -top-2 -right-2 bg-gold text-black text-[10px] font-bold px-1.5 py-0.5 rounded-full">
                  -{pkg.savings}%
                </span>
              ) : null}
              <p className="text-white font-bold text-lg">{pkg.credits}</p>
              <p className="text-text-muted text-xs">credits</p>
              <p className="text-gold font-semibold text-sm mt-1">{pkg.price}</p>
            </Link>
          ))}
        </div>

        {/* CTA */}
        <Link
          href="/credits/buy"
          className="block w-full bg-gold hover:bg-gold-light text-black font-bold text-center py-3 rounded-xl transition-all shadow-glow"
          onClick={handleDismiss}
        >
          Top Up Now
        </Link>
      </div>
    </div>
  );
}
