import React from "react"
import { useEffect } from "react"
import { usePush } from "../usePush"
import pushPublicKey from "../../pushPublicKey"
import urlB64ToUint8Array from "../../b64ToUInt8"

export default function EnableNotifications({
  onSubscribe,
}: {
  onSubscribe: () => void
}) {
  return (
    <div>
      <h1>Allow Notifications</h1>
      <div>
        Tack Up Now requires your permission to send notifications in order to
        function properly
      </div>
      <EnableButton onSubscribe={onSubscribe} />
    </div>
  )
}

function EnableButton({ onSubscribe }: { onSubscribe: () => void }) {
  const { subscribeToPush, requestPermission, canSendPush } = usePush()

  function subscribe() {
    requestPermission()
  }

  useEffect(() => {
    if (!canSendPush) return

    subscribeToPush(
      urlB64ToUint8Array(pushPublicKey) as any,
      async (subscription) => {
        await navigator.serviceWorker.ready.then((registration) => {
          registration.active?.postMessage({
            type: "subscribed",
            subscription: subscription.toJSON(),
          })
        })
        onSubscribe()
      }
    )
  }, [canSendPush])

  return <button onClick={subscribe}>Enable Notifications</button>
}
