import React, { useState } from 'react'
import { useRouter } from 'next/router'
import Head from 'next/head'
import Footer from '../../components/footer'
import Header from '../../components/header'
import Input from '../../components/input'
import { getBaseURL } from '../../helpers/url'

export default function Login() {
  const router = useRouter()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const isValid = !!username.length && !!password.length

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()

    try {
      await fetch('/api/admin/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
        }),
      }).then((response) => {
        if (!response.ok) {
          console.error('Unable to login', response.status, response.statusText)
          return
        }
        const redirect = Array.isArray(router.query?.redirect)
          ? router.query.redirect[0]
          : router.query?.redirect

        router.push(redirect || getBaseURL())
      })
    } catch (error) {
      console.error('Unable to login', error)
    }
  }

  return (
    <>
      <Head>
        <title>Pfadi Bussle Admin</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header label="Pfadi Bussle Admin Login" />
      <main className="main w-64">
        <form className="form" onSubmit={onSubmit}>
          <Input
            label="Username"
            name="username"
            onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
              setUsername(event.target.value)
            }
          />
          <Input
            label="Password"
            name="password"
            type="password"
            onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
              setPassword(event.target.value)
            }
          />
          <button
            type="submit"
            className="btn btn-blue ml-0"
            disabled={!isValid}
          >
            Login
          </button>
        </form>
      </main>
      <Footer />
    </>
  )
}
