import React, { useEffect, useState } from "react";

const InstallPWA = () => {
  const [deferredPrompt, setDeferredPrompt] = useState(null);
  const [installed, setInstalled] = useState(true);

  useEffect(() => {
    window.addEventListener("beforeinstallprompt", (e) => {
      e.preventDefault();
      setDeferredPrompt(e);
    });
    window.addEventListener("appinstalled", () => {
      // Clear the deferredPrompt so it can be garbage collected
      setDeferredPrompt(null);
      // Optionally, send analytics event to indicate successful install
      console.log("PWA was installed");
    });
  }, []);
  useEffect(() => {
    console.log("deferredPrompt: ", deferredPrompt);
    if (deferredPrompt) setInstalled(false);
  }, [deferredPrompt]);

  const onInstallClick = async () => {
    try {
      console.log("install");
      console.log("install");
      // Show the install prompt
      deferredPrompt.prompt();
      // Wait for the user to respond to the prompt
      const { outcome } = await deferredPrompt.userChoice;
      // Optionally, send analytics event with outcome of user choice
      console.log(`User response to the install prompt: ${outcome}`);
      // We've used the prompt, and can't use it again, throw it away
      setDeferredPrompt(null);
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      <button type="button" onClick={() => onInstallClick()}>
        Click Here
      </button>
    </>
  );
};

export default InstallPWA;
