import { h, type FunctionComponent } from 'preact'
import { useCallback } from 'preact/hooks'
import rek, { type FetchError } from 'rek'

import useRequestState from '../../shared/hooks/use_request_state.ts'
import Button from './button.tsx'
import Input from './input.tsx'
import Message from './message.tsx'

const ChangePasswordForm: FunctionComponent = () => {
  const [{ error, pending, success }, actions] = useRequestState<FetchError>()

  const changePassword = useCallback(async (e: SubmitEvent & { currentTarget: HTMLFormElement }) => {
    e.preventDefault()

    actions.pending()

    try {
      const params = new URLSearchParams(location.search)

      await rek.post('/auth/change-password', {
        password: e.currentTarget.password.value,
        token: params.get('token'),
        email: params.get('email'),
      })

      actions.success()
    } catch (err) {
      actions.error(err as FetchError)
    }
  }, [])

  return success ? (
    <Message type='success' noMargin>
      Password changed! Head over to <a href='/admin/login'>the login page</a> to try it out!
    </Message>
  ) : (
    <form onSubmit={changePassword}>
      {error && (
        <Message type='error'>
          {error.status}: {error.body?.message || error.message}
        </Message>
      )}

      <Input name='password' label='Password' type='password' required />
      <Input name='confirmPassword' label='Confirm Password' type='password' sameAs='password' required />
      <Button disabled={pending}>Change Password</Button>
    </form>
  )
}

export default ChangePasswordForm
