import { ref, onMounted, onUnmounted } from "vue";
import { modalController, alertController } from "@ionic/vue";
import IosInstallTutorial from "../../components/IosInstallTutorial.vue";

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

type Options = {
  promptMessagePopup?: string;
  storageKey?: string;
};

export function usePwaInstall(options: Options = {}) {
  const deferredPrompt = ref<BeforeInstallPromptEvent | null>(null);
  const showInstallButton = ref(false);

  const {
    promptMessagePopup = "Vous pouvez installer cette page sur votre appareil pour un accès plus rapide et une meilleure expérience.",
    storageKey = "hasShownPwaInstallAlert",
  } = options;

  const isMobile = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
  };

  const isIosSafari = () => {
    const ua = window.navigator.userAgent;
    const iOS = /iPad|iPhone|iPod/.test(ua);
    const webkit = /WebKit/i.test(ua);
    return iOS && webkit && !/(CriOS|FxiOS|OPiOS|mercury)/i.test(ua);
  };

  const handleBeforeInstallPrompt = (e: BeforeInstallPromptEvent) => {
    console.log("BeforeInstallPrompt event captured");
    e.preventDefault();
    deferredPrompt.value = e;
    if (isMobile()) {
      showInstallButton.value = true;
    }
  };

  const openIosInstallModal = async () => {
    const modal = await modalController.create({
      component: IosInstallTutorial,
      cssClass: "ios-install-modal",
    });
    return modal.present();
  };

  const handleInstallClick = async () => {
    if (isIosSafari()) {
      await openIosInstallModal();
      return;
    }

    if (!deferredPrompt.value) {
      alert(
        'Pour installer l\'application:\n1. Appuyez sur le bouton "Partager"\n2. Faites défiler et appuyez sur "Sur l\'écran d\'accueil"'
      );
      return;
    }

    deferredPrompt.value.prompt();
    const { outcome } = await deferredPrompt.value.userChoice;

    if (outcome === "accepted") {
      showInstallButton.value = false;
    }
    deferredPrompt.value = null;
  };

  onMounted(() => {
    console.log("Mounting PWA install handler");
    if ("BeforeInstallPromptEvent" in window) {
      console.log("BeforeInstallPromptEvent is supported");
    }

    if (window.matchMedia("(display-mode: standalone)").matches) {
      console.log("App is already installed");
    } else {
      if (isMobile()) {
        showInstallButton.value = true;
      }
    }

    window.addEventListener(
      "beforeinstallprompt",
      handleBeforeInstallPrompt as EventListener
    );
  });

  onUnmounted(() => {
    window.removeEventListener(
      "beforeinstallprompt",
      handleBeforeInstallPrompt as EventListener
    );
  });

  const showInstallAlert = async () => {
    if (window.matchMedia("(display-mode: standalone)").matches) {
      console.log("App is already installed, not showing install alert");
      return;
    }
    const hasShownInstallAlert = localStorage.getItem(storageKey);
    if (hasShownInstallAlert === "true") {
      console.log("Install alert has been shown before, not showing again");
      return;
    }

    const alert = await alertController.create({
      header: "Installer l'application",
      message: promptMessagePopup,
      buttons: [
        {
          text: "Plus tard",
          role: "cancel",
          cssClass: "!text-secondary",
          handler: () => {
            console.log("Install alert dismissed");
            localStorage.setItem(storageKey, "true");
          },
        },
        {
          text: "Installer",
          cssClass: "!text-secondary",
          handler: () => {
            console.log("Install button clicked from alert");
            localStorage.setItem(storageKey, "true");
            handleInstallClick();
          },
        },
      ],
    });

    await alert.present();
  };

  return {
    showInstallButton,
    handleInstallClick,
    showInstallAlert,
  };
}
