/* eslint-disable import/no-unresolved */
import { useCallback, useEffect, useState } from "react"
import type { Vault, OnePassword } from "opvault.js"
import { useIdleTimer } from "react-idle-timer/modern"
import { VaultView } from "./pages/Vault"
import { VaultPicker } from "./pages/VaultPicker"
import { Key, useStorage } from "./utils/localStorage"

export const App: React.FC = () => {
  const [instance, setInstance] = useState<OnePassword>()
  const [vault, setVault] = useState<Vault>()

  const [enableAutoLock] = useStorage(Key.ENABLE_AUTO_LOCK)
  const [autolockAfter] = useStorage(Key.AUTO_LOCK_AFTER)

  const onLock = useCallback(() => {
    vault?.lock()
    setVault(undefined)
  }, [vault])

  const onAutoLock = useCallback(() => {
    if (enableAutoLock) {
      onLock()
    }
  }, [onLock, enableAutoLock])

  const { reset, pause } = useIdleTimer({
    timeout: autolockAfter * 1000,
    onIdle: onAutoLock,
  })

  useEffect(() => {
    if (vault) {
      reset()
    } else {
      pause()
    }
  }, [vault])

  if (!vault) {
    return (
      <VaultPicker
        instance={instance}
        setInstance={setInstance}
        vault={vault}
        setVault={setVault}
      />
    )
  }

  return <VaultView onLock={onLock} vault={vault} />
}
