import {
  json,
  type LoaderFunctionArgs,
  type MetaFunction,
} from "@remix-run/node"
import { useLoaderData } from "@remix-run/react"
import React, { Suspense, useEffect, useState } from "react"
import coerceSemver from "semver/functions/coerce"
import versionAtLeast from "semver/functions/gte"
import UAParser from "ua-parser-js"
import InstallPrompts from "../install/InstallPrompts"
import useInstallState from "../useInstallState"
import ClientOnly from "../ClientOnly"

export const meta: MetaFunction = () => {
  return [
    { title: "Tack Up Now!" },
    { name: "description", content: "Get equinelive notifications" },
  ]
}

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const userAgent = request.headers.get("user-agent")
  const parsedUserAgent = new UAParser(userAgent ?? "")
  const os = parsedUserAgent.getOS()
  const isMobileSafari = parsedUserAgent.getBrowser().name === "Mobile Safari"
  const isSupported =
    os.name !== "iOS" ||
    versionAtLeast(coerceSemver(os.version) ?? "0.0.0", "16.4.0")

  return json({
    isSupported,
    isMobileSafari,
    name: os.name,
    version: os.version,
  })
}

export default function Index() {
  const { isSupported, isMobileSafari, name, version } =
    useLoaderData<typeof loader>()

  console.log(name, version)

  return (
    <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
      <Suspense>
        <LandingMessage
          isSupported={isSupported}
          isMobileSafari={isMobileSafari}
        />
      </Suspense>
    </div>
  )
}

function LandingMessage({
  isSupported,
  isMobileSafari,
}: {
  isSupported: boolean
  isMobileSafari: boolean
}) {
  const { installed } = useInstallState({ isSupported, isMobileSafari })

  const [isInstalled, setIsInstalled] = useState(installed)

  return (
    <ClientOnly fallback={<div>Loading</div>}>
      {() =>
        isInstalled ? (
          <div>Your Notifications</div>
        ) : (
          <InstallPrompts
            isMobileSafari={isMobileSafari}
            isSupported={isSupported}
            notificationsEnabled={false}
            onInstallComplete={() => setIsInstalled(true)}
          />
        )
      }
    </ClientOnly>
  )
}
