import { useEffect, useState } from "react";
import { Download, X } from "lucide-react";
import { useInstallPrompt, setInstallPromptEvent } from "@/hooks/use-install-prompt";

const DISMISS_KEY = "niyamah-install-dismissed-at";
const DISMISS_TTL = 1000 * 60 * 60 * 24 * 7; // 7 days

export function InstallPrompt() {
  const { evt, prompt } = useInstallPrompt();
  const [show, setShow] = useState(false);
  const [standalone, setStandalone] = useState(false);
  const [supported, setSupported] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    // Detect standalone (installed) mode and keep watching for changes
    const mql = window.matchMedia("(display-mode: standalone)");
    const computeStandalone = () =>
      mql.matches || (window.navigator as any).standalone === true;
    setStandalone(computeStandalone());
    const onDisplayChange = () => setStandalone(computeStandalone());
    mql.addEventListener?.("change", onDisplayChange);

    // Only browsers that actually support the install prompt fire this event
    const supportsBIP = "onbeforeinstallprompt" in window;
    setSupported(supportsBIP);

    const dismissedAt = Number(localStorage.getItem(DISMISS_KEY) || 0);
    const dismissedRecently =
      dismissedAt && Date.now() - dismissedAt < DISMISS_TTL;

    const handler = (e: Event) => {
      e.preventDefault();
      if (computeStandalone()) return; // never show if already installed
      if (dismissedRecently) return;
      setInstallPromptEvent(e as any);
      setShow(true);
    };

    if (supportsBIP && !computeStandalone()) {
      window.addEventListener("beforeinstallprompt", handler);
    }

    const installed = () => {
      setShow(false);
      setStandalone(true);
      setInstallPromptEvent(null);
    };
    window.addEventListener("appinstalled", installed);

    return () => {
      window.removeEventListener("beforeinstallprompt", handler);
      window.removeEventListener("appinstalled", installed);
      mql.removeEventListener?.("change", onDisplayChange);
    };
  }, []);

  const onInstall = async () => {
    const result = await prompt();
    if (result.outcome === "accepted") {
      setShow(false);
    }
  };

  const onClose = () => {
    localStorage.setItem(DISMISS_KEY, String(Date.now()));
    setShow(false);
  };

  if (standalone || !supported || !show || !evt) return null;

  return (
    <div
      className="fixed bottom-4 left-1/2 -translate-x-1/2 z-[100] w-[92%] max-w-md px-1"
      style={{ animation: "install-rise 420ms cubic-bezier(0.22, 1, 0.36, 1)" }}
    >
      <style>{`
        @keyframes install-rise {
          0% { opacity: 0; transform: translate(-50%, 24px) scale(0.96); }
          100% { opacity: 1; transform: translate(-50%, 0) scale(1); }
        }
        @keyframes install-shimmer {
          0% { transform: translateX(-120%); }
          60%, 100% { transform: translateX(220%); }
        }
        @keyframes install-glow {
          0%, 100% { box-shadow: 0 10px 40px -10px color-mix(in oklab, var(--primary) 55%, transparent); }
          50% { box-shadow: 0 14px 50px -8px color-mix(in oklab, var(--accent) 70%, transparent); }
        }
        @keyframes install-pulse-dot {
          0%, 100% { transform: scale(1); opacity: 0.9; }
          50% { transform: scale(1.35); opacity: 0.4; }
        }
      `}</style>

      <div
        className="rounded-2xl p-[1.5px] bg-gradient-to-r from-primary via-accent to-primary"
        style={{ animation: "install-glow 3.2s ease-in-out infinite" }}
      >
        <div className="relative overflow-hidden rounded-[14px] bg-background/95 backdrop-blur-xl px-3 py-3 flex items-center gap-3 border border-border/40">
          {/* subtle brand wash */}
          <div
            aria-hidden
            className="pointer-events-none absolute inset-0 opacity-60"
            style={{
              background:
                "radial-gradient(120% 80% at 0% 0%, color-mix(in oklab, var(--primary) 14%, transparent), transparent 60%), radial-gradient(120% 80% at 100% 100%, color-mix(in oklab, var(--accent) 14%, transparent), transparent 60%)",
            }}
          />

          {/* icon tile */}
          <div className="relative shrink-0 h-11 w-11 rounded-xl grid place-items-center bg-gradient-to-br from-primary to-accent text-primary-foreground shadow-lg shadow-primary/30">
            <Download className="h-5 w-5" strokeWidth={2.5} />
            <span
              aria-hidden
              className="absolute -top-0.5 -right-0.5 h-2.5 w-2.5 rounded-full bg-accent ring-2 ring-background"
              style={{ animation: "install-pulse-dot 1.6s ease-in-out infinite" }}
            />
          </div>

          {/* copy */}
          <div className="relative flex-1 min-w-0">
            <p className="text-sm font-semibold leading-tight text-foreground truncate">
              নিয়ামাহ্ অ্যাপ ইনস্টল করুন
            </p>
            <p className="text-[11px] text-muted-foreground leading-snug truncate">
              দ্রুত অ্যাক্সেস পেতে হোম স্ক্রিনে যোগ করুন
            </p>
          </div>

          {/* CTA */}
          <button
            onClick={onInstall}
            className="relative shrink-0 overflow-hidden rounded-xl text-primary-foreground text-xs font-bold px-3.5 py-2 bg-gradient-to-r from-primary to-accent shadow-md shadow-primary/30 transition-transform duration-200 active:scale-95 hover:brightness-110"
          >
            <span className="relative z-10">ইনস্টল</span>
            <span
              aria-hidden
              className="absolute inset-0 -translate-x-full pointer-events-none"
              style={{
                background:
                  "linear-gradient(110deg, transparent 30%, rgba(255,255,255,0.55) 50%, transparent 70%)",
                animation: "install-shimmer 2.6s ease-in-out infinite",
              }}
            />
          </button>

          {/* Close */}
          <button
            onClick={onClose}
            aria-label="বন্ধ করুন"
            className="relative shrink-0 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/60 p-1.5 transition-all duration-200 active:rotate-90"
          >
            <X className="h-4 w-4" />
          </button>
        </div>
      </div>
    </div>
  );
}
