import { h, type FunctionComponent, type TargetedSubmitEvent } from 'preact'
import type { FetchError } from 'rek'
import { useCallback } from 'preact/hooks'
import { useAuth } from '../../shared/contexts/auth.tsx'
import rek from 'rek'

import useRequestState from '../../shared/hooks/use_request_state.ts'
import Input from './input.tsx'
import s from './login_form.module.scss'

const LoginForm: FunctionComponent = () => {
  const [{ error, pending }, actions] = useRequestState<FetchError>()
  const { user } = useAuth()

  const login = useCallback(async (e: TargetedSubmitEvent<HTMLFormElement>) => {
    e.preventDefault()

    actions.pending()

    const form = e.currentTarget

    try {
      const response = await rek.post(
        '/auth/login',
        {
          email: form.email.value,
          password: form.password.value,
        },
        { response: false },
      )

      const lastVisit = response.headers.get('x-last-visit')

      if (lastVisit) {
        localStorage.setItem('lastVisit', lastVisit)
      }

      const result = await response.json()

      user.value = result
    } catch (err) {
      actions.error(err as FetchError)
    }
  }, [])

  return (
    <form onSubmit={login} className={s.root}>
      {error && <div className={s.error}>Error: {error.body?.message || error.message}</div>}

      <Input className={s.input} name='email' label='Email' placeholder='Email' type='email' autoFocus required />
      <Input
        className={s.input}
        type='password'
        name='password'
        label='Password'
        placeholder='Password'
        autoComplete='current-password'
        required
      />

      <button className={s.button} type='submit' disabled={pending}>
        Login
      </button>

      <ul className={s.links}>
        <li>
          <a href='/admin/forgot-password'>Forgot your password?</a>
        </li>
        <li>
          <a href='/admin/register'>No account? Register a new</a>
        </li>
      </ul>
    </form>
  )
}

export default LoginForm
