import { useCallback, useEffect, useState } from "react"
import type { Vault } from "opvault.js"
import { OnePassword } from "opvault.js"
import { Unlock } from "./Unlock"
import { electronAdapter } from "../../utils/ipc-adapter"
import { get, remove, set, Key } from "../../utils/localStorage"
import { PickOPVault } from "./Picker"

interface VaultPickerProps {
  instance: OnePassword | undefined
  setInstance(value?: OnePassword): void
  vault: Vault | undefined
  setVault(vault?: Vault): void
}

export const VaultPicker: React.FC<VaultPickerProps> = ({
  instance,
  setInstance,
  vault,
  setVault,
}) => {
  const [vaultPath, setVaultPath] = useState("")

  const unlock = useCallback(
    async (profile: string, password: string) => {
      const vault = await instance!.getProfile(profile!)
      await vault.unlock(password)
      setVault(vault)
    },
    [instance, setVault]
  )

  const clearInstance = useCallback(() => {
    setVaultPath("")
    setInstance(undefined)
  }, [setInstance])

  useEffect(() => {
    const existingPath = get(Key.LAST_VAULT_PATH)
    if (existingPath != null) {
      setVaultPath(existingPath)
    }
  }, [])

  useEffect(() => {
    if (vaultPath) {
      const instance = new OnePassword({
        path: vaultPath,
        adapter: electronAdapter,
      })
      setInstance(instance)
      set(Key.LAST_VAULT_PATH, vaultPath)
    } else {
      setInstance(undefined)
      remove(Key.LAST_VAULT_PATH)
    }
  }, [vaultPath, setInstance])

  if (!instance) {
    return <PickOPVault setPath={setVaultPath} />
  }
  if (!vault) {
    return (
      <Unlock
        vaultPath={vaultPath}
        onReturn={clearInstance}
        instance={instance}
        onUnlock={unlock}
      />
    )
  }
  return null
}
