"use client";

import { useCallback, useEffect, useState } from "react";
import {
  BeforeInstallPromptEvent,
  dismissInstallPrompt,
  isDismissed,
  isIosDevice,
  isStandaloneMode,
} from "@/lib/pwa/install";

export function usePwaInstall() {
  const [deferredPrompt, setDeferredPrompt] =
    useState<BeforeInstallPromptEvent | null>(null);
  const [visible, setVisible] = useState(false);
  const [installing, setInstalling] = useState(false);
  const isIos = isIosDevice();

  useEffect(() => {
    if (isStandaloneMode() || isDismissed()) return;

    const onBeforeInstall = (event: Event) => {
      event.preventDefault();
      setDeferredPrompt(event as BeforeInstallPromptEvent);
      setVisible(true);
    };

    const onInstalled = () => {
      setVisible(false);
      setDeferredPrompt(null);
    };

    window.addEventListener("beforeinstallprompt", onBeforeInstall);
    window.addEventListener("appinstalled", onInstalled);

    const timer = window.setTimeout(() => {
      if (isStandaloneMode() || isDismissed()) return;
      if (isIosDevice()) {
        setVisible(true);
      }
    }, 2000);

    return () => {
      window.clearTimeout(timer);
      window.removeEventListener("beforeinstallprompt", onBeforeInstall);
      window.removeEventListener("appinstalled", onInstalled);
    };
  }, []);

  const install = useCallback(async () => {
    if (!deferredPrompt) return false;

    setInstalling(true);
    try {
      await deferredPrompt.prompt();
      const choice = await deferredPrompt.userChoice;
      if (choice.outcome === "accepted") {
        setVisible(false);
        setDeferredPrompt(null);
        return true;
      }
      return false;
    } finally {
      setInstalling(false);
    }
  }, [deferredPrompt]);

  const close = useCallback((remember = true) => {
    setVisible(false);
    if (remember) dismissInstallPrompt();
  }, []);

  return {
    visible,
    installing,
    isIos,
    canNativeInstall: Boolean(deferredPrompt),
    install,
    close,
  };
}
