import React, { useEffect, useState } from 'react'
import { useStorage } from '../lib/use-storage'
import { startAuth, TOKEN_STORAGE_KEY } from '../services/auth'
import { KINDLE_OWNED_CONTENT_REQUEST, startKindleAuth } from '../services/kindle'
import { Step, StepSuccess } from './setup/step'

export const Setup: React.FC = () => {
  const [kindleWindow, setKindleWindow] = useState(null)
  const isAuthenticated = !!useStorage(TOKEN_STORAGE_KEY)
  const hasSetupKindle = !!useStorage(KINDLE_OWNED_CONTENT_REQUEST)

  useEffect(() => {
    if (hasSetupKindle && kindleWindow) {
      kindleWindow?.close()
      setKindleWindow(null)
    }
  }, [hasSetupKindle])

  return (
    <ul className="mt-20">
      <Step
        label="Install Chrome Extension"
        description="You've done this!"
        complete={true} />

      <Step
        label="Authenticate with Reflect"
        description="Make this extension happy."
        actionLabel="Authenticate"
        onClickAction={() => startAuth()}
        complete={isAuthenticated}
        current={!isAuthenticated} />

      <Step
        label="Authenticate with Amazon"
        description="Get your Kindle Library synced."
        actionLabel="Authenticate"
        onClickAction={() => setKindleWindow(startKindleAuth())}
        complete={hasSetupKindle}
        current={isAuthenticated && !hasSetupKindle} />

      <StepSuccess
        label="Boom!"
        description="You're all set"
        current={isAuthenticated && hasSetupKindle} />
    </ul>
  )
}

