import React, { useState } from 'react'
import sleep from '../lib/sleep'
import { useStorage } from '../lib/use-storage'
import { TOKEN_STORAGE_KEY } from '../services/auth'
import { client } from '../services/client'
import { Button } from './button'
import { usePage } from './use-page'

type PopupState = 'default' | 'loading' | 'success'

export const Popup: React.FC = () => {
  const [subject, setSubject] = useState<string>('')
  const [body, setBody] = useState<string>('')
  const [state, setState] = useState<PopupState>('default')

  usePage(({
    ogTitle,
    ogDescription,
    metaDescription,
    title,
    url,
    selectionText,
  }) => {
    const description = selectionText || ogDescription || metaDescription
    const defaultSubject = ogTitle || title
    const defaultBody = `${url}\n\n${description}`.trim()

    if ( !subject ) setSubject(defaultSubject)
    if ( !body ) setBody(defaultBody)
  })

  const token = useStorage(TOKEN_STORAGE_KEY)
  client.setToken(token)

  const createNote = async () => {
    setState('loading')
    await client.createNote({
      subject,
      content_markdown: body
    })
    setState('success')
    await sleep(1000)
    window.close()
  }

  return (
    <main style={{width: 350, minHeight: 250}} className="px-3 py-3 flex flex-col space-y-3 relative">
      <input
        autoFocus
        value={subject}
        onChange={(e) => setSubject(e.target.value)}
        placeholder="Note title"
        className="flex-none form-input block w-full min-w-0 rounded-md transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

      <textarea
        value={body}
        onChange={(e) => setBody(e.target.value)}
        className="flex-grow form-textarea block w-full min-w-0 rounded-md transition duration-150 ease-in-out sm:text-sm sm:leading-5" />

      <footer className="flex justify-end">
        <Button
          onClick={createNote}
          state={state}
          label="Create note"
          loadingLabel="Creating..." />
      </footer>
    </main>
  )
}

