import Seo from "components/SEO";
import { NextPage } from "next";
// @ts-ignore
import { useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
const InstallPage:NextPage = () => {
    const button = useRef(null)
    const [defferedPrompt, setDefferedPrompt] = useState<BeforeInstallPromptEvent>(null)
    // Is PWA installed?
    let [isAppInstalled, setIsAppInstalled] = useState(false);
    // Button on click
    function onClick() {
        if (!defferedPrompt) return
        defferedPrompt.prompt();
        defferedPrompt.userChoice.then((choice: { outcome: string; }) => {
            if (choice.outcome === 'dismissed') {
                toast.error("Prompt was dismissed", { duration: 7500 })
            }
            setDefferedPrompt(null);
        })
    }
    // Runs once when the browser is ready
    useEffect(() => {
        // Checks if the PWA app is already installed
        setIsAppInstalled(window.matchMedia("(display-mode: standalone)").matches)
        // get event listener for when the prompt was triggered
        const handler = (e: any) => setDefferedPrompt(e);
        
        window.addEventListener("beforeinstallprompt", handler);
        return () => window.removeEventListener("transitionend", handler);
    }, [])
    return (
        <>
        <Seo templateTitle="Install"    />

        <div className="grid place-items-center h-full">
            <button onClick={onClick} ref={button} disabled={isAppInstalled} className="w-16 h-16 bg-red-700 disabled:bg-green-500">
                {isAppInstalled ? "Installed" : "Install"}
            </button>
            <label className="text-sm absolute mt-20 text-common-black">
                Note: If the button is not working find the install app icon/text and click it
            </label>
        </div>
        </>
    );
}
interface BeforeInstallPromptEvent extends Event {

    /**
     * Returns an array of DOMString items containing the platforms on which the event was dispatched.
     * This is provided for user agents that want to present a choice of versions to the user such as,
     * for example, "web" or "play" which would allow the user to chose between a web version or
     * an Android version.
     */
    readonly platforms: Array<string>;
  
    /**
     * Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed".
     */
    readonly userChoice: Promise<{
      outcome: 'accepted' | 'dismissed',
      platform: string
    }>;
  
    /**
     * Allows a developer to show the install prompt at a time of their own choosing.
     * This method returns a Promise.
     */
    prompt(): Promise<void>;
  
  }
  
export default InstallPage;