"use client";

import { useEffect } from "react";
import { verifyLicenseInBackground } from "@/app/actions/license";
import { ShieldAlert, PhoneCall, AlertTriangleIcon } from "lucide-react";
import { useRouter } from "next/navigation";

export default function LicenseLockout({ validUntil }: { validUntil: Date | null }) {
  const router = useRouter();

  useEffect(() => {
    // Silently verify the license on the background upon app start
    verifyLicenseInBackground().then((res) => {
      // If Hub authorized an update (renewed or revoked), trigger a global Server React tree refresh
      if (res && res.updated) {
        router.refresh();
      }
    });
  }, [router]);

  if (!validUntil) return null; // App is not set up yet
  
  const now = new Date();
  const validUntilDate = new Date(validUntil);
  const timeDiff = validUntilDate.getTime() - now.getTime();
  const daysLeft = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
  
  const isExpired = validUntilDate < now;
  // We explicitly check the exact 1970 date to show the "Revoked" state vs natural expiry
  const isRevoked = validUntilDate.getTime() === 0;

  const handleExternalLink = (e: React.MouseEvent<HTMLAnchorElement>, url: string) => {
    e.preventDefault();
    if (typeof window !== 'undefined' && 'require' in window && navigator.userAgent.includes('Electron')) {
      try {
        const electron = (window as any).require('electron');
        electron.shell.openExternal(url);
        return;
      } catch (err) { console.error(err); }
    }
    window.open(url, '_blank');
  };

  const renewButton = (
    <a href="#" onClick={(e) => handleExternalLink(e, "https://qocteam.com/tukan")} className="mt-4 flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-6 rounded-xl transition-colors shadow-sm w-full">
      تمدید یا ارتقا لایسنس 💎
    </a>
  );

  if (isExpired) {
    return (
      <div className="fixed inset-0 z-[99999] flex items-center justify-center bg-zinc-950/90 backdrop-blur-md" dir="rtl">
        <div className="max-w-md w-full bg-zinc-900 border border-red-900/50 p-8 rounded-3xl shadow-2xl text-center space-y-6 relative overflow-hidden">
          {/* Animated Warning Background Ring */}
          <div className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-red-600/20 rounded-full blur-3xl animate-pulse" />
          
          <div className="relative mx-auto w-24 h-24 bg-red-500/10 rounded-full flex items-center justify-center border border-red-500/20">
            <ShieldAlert className="w-12 h-12 text-red-500" />
          </div>

          <div className="space-y-2 relative">
            <h1 className="text-3xl font-black text-white tracking-tight">
              دسترســی مســدود شــد
            </h1>
            <p className="text-zinc-400 text-sm leading-relaxed max-w-[280px] mx-auto font-medium">
              {isRevoked 
                ? "پروانه فعالیت سیستم شما از سوی پنل مدیریت مرکزی بنا به دلایلی تعلیق شده است." 
                : "مدت زمان اعتبار لایسنس نرم‌افزار به پایان رسیده است و سیستم به طور خودکار فریز گردید."}
            </p>
          </div>

          <div className="bg-zinc-950/50 rounded-2xl p-4 border border-white/5 space-y-3 relative">
            <div className="flex items-center justify-center gap-2 text-red-400 font-bold mb-1">
              <PhoneCall className="w-5 h-5" />
              <span>واحد پشتیبانی و تمدید</span>
            </div>
            <div className="text-2xl font-black text-white tracking-widest font-sans">
              09009091092
            </div>
            <p className="text-xs text-zinc-500">
              برای رفع تعلیق لطفاً با شماره بالا تماس بگیرید. پشتیبانان ما در اسرع وقت پاسخگو خواهند بود.
            </p>
            {renewButton}
          </div>
        </div>
      </div>
    );
  }

  // Warning Banner for 1-14 days
  if (daysLeft <= 14 && daysLeft > 0 && !isRevoked) {
    return (
      <div className="fixed bottom-4 left-4 z-[99998] bg-rose-50 border border-rose-200 text-rose-900 p-4 rounded-2xl shadow-xl w-80 animate-in slide-in-from-bottom-5 duration-500" dir="rtl">
        <div className="flex items-center gap-2 font-bold mb-2">
            <AlertTriangleIcon className="w-5 h-5 text-rose-600" />
            <span>هشدار اتمام لایسنس</span>
        </div>
        <p className="text-xs mb-3 font-medium text-rose-800 leading-relaxed">
            فقط <span className="font-black text-base">{daysLeft} روز</span> تا پایان اعتبار نرم‌افزار شما باقی مانده است. برای جلوگیری از مسدود شدن دسترسی، همین امروز اقدام کنید.
        </p>
        <a href="#" onClick={(e) => handleExternalLink(e, "https://qocteam.com/tukan")} className="flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-sm w-full text-xs">
            تمدید آنلاین لایسنس 💎
        </a>
      </div>
    );
  }

  return null;
}
