"use client";

import { useEffect, useMemo, useState } from "react";
import { Download, Smartphone } from "lucide-react";

import { Button } from "@/components/ui/button";

interface BeforeInstallPromptEvent extends Event {
  prompt: () => Promise<void>;
  userChoice: Promise<{
    outcome: "accepted" | "dismissed";
    platform: string;
  }>;
}

declare global {
  interface WindowEventMap {
    beforeinstallprompt: BeforeInstallPromptEvent;
  }
}

function isStandaloneMode() {
  if (typeof window === "undefined") {
    return false;
  }

  const browserStandalone = window.matchMedia("(display-mode: standalone)").matches;
  const iosStandalone = Boolean((window.navigator as Navigator & { standalone?: boolean }).standalone);
  return browserStandalone || iosStandalone;
}

function isIosMobile() {
  if (typeof window === "undefined") {
    return false;
  }

  const userAgent = window.navigator.userAgent.toLowerCase();
  const isAppleDevice = /iphone|ipad|ipod/.test(userAgent);
  const isWebkit = /webkit/.test(userAgent);
  const isExcluded = /crios|fxios|edgios|opios/.test(userAgent);
  return isAppleDevice && isWebkit && !isExcluded;
}

export function InstallAppButton({ compact = false }: { compact?: boolean }) {
  const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
  const [installed, setInstalled] = useState(() => {
    if (typeof window === "undefined") {
      return false;
    }

    return isStandaloneMode();
  });
  const [hint, setHint] = useState<string | null>(null);

  useEffect(() => {
    const onBeforeInstallPrompt = (event: BeforeInstallPromptEvent) => {
      event.preventDefault();
      setDeferredPrompt(event);
    };

    const onAppInstalled = () => {
      setInstalled(true);
      setDeferredPrompt(null);
      setHint("Installed. You can launch video.haus from your home screen.");
    };

    window.addEventListener("beforeinstallprompt", onBeforeInstallPrompt);
    window.addEventListener("appinstalled", onAppInstalled);

    return () => {
      window.removeEventListener("beforeinstallprompt", onBeforeInstallPrompt);
      window.removeEventListener("appinstalled", onAppInstalled);
    };
  }, []);

  useEffect(() => {
    if (!hint) {
      return;
    }

    const timeout = window.setTimeout(() => {
      setHint(null);
    }, 4500);

    return () => {
      window.clearTimeout(timeout);
    };
  }, [hint]);

  const buttonLabel = useMemo(() => {
    if (installed) {
      return "Installed";
    }

    return "Install as App";
  }, [installed]);

  const handleInstall = async () => {
    if (installed) {
      setHint("video.haus is already installed on this device.");
      return;
    }

    if (deferredPrompt) {
      await deferredPrompt.prompt();
      const choice = await deferredPrompt.userChoice;
      if (choice.outcome === "accepted") {
        setHint("Install started. Check your home screen in a moment.");
      } else {
        setHint("Install prompt dismissed.");
      }
      setDeferredPrompt(null);
      return;
    }

    if (isIosMobile()) {
      setHint("On iPhone/iPad: tap Share, then choose Add to Home Screen.");
      return;
    }

    setHint("Install option unavailable here. Use your browser menu: Install app / Add to Home Screen.");
  };

  return (
    <div className="relative">
      <Button
        variant={compact ? "outline" : "secondary"}
        size="sm"
        className="border-white/20 bg-slate-900/70 text-slate-100 hover:bg-slate-800"
        onClick={() => {
          void handleInstall();
        }}
      >
        {installed ? <Smartphone data-icon="inline-start" /> : <Download data-icon="inline-start" />}
        {buttonLabel}
      </Button>
      {hint ? (
        <div className="absolute right-0 top-full z-[80] mt-2 w-72 rounded-lg border border-white/15 bg-slate-950 px-3 py-2 text-xs leading-relaxed text-slate-200 shadow-xl">
          {hint}
        </div>
      ) : null}
    </div>
  );
}
