"use client";
import React, { type ReactElement, useState } from 'react'
import Button from '@/Components/Buttons/Button'
import Input from '@/Components/Inputs/Input'
import AuthApi from '@/Components/Auth/AuthApi'

interface IRequestPasswordReset {
  onSuccess?: () => void
  onFailure?: () => void
}

export default function RequestPasswordReset({
  onSuccess,
  onFailure
}: IRequestPasswordReset): ReactElement {
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e?: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement, MouseEvent> | React.FormEvent<HTMLFormElement>): Promise<void> => {
    e?.preventDefault()
    if (loading) return
    try {
      setLoading(true)
      const response = await AuthApi.requestPasswordReset(email)
      console.log(response)
      setLoading(false)
      onSuccess?.()
    } catch (error) {
      console.error(error)
      setLoading(false)
      onFailure?.()
    }
  }
  return (
    <form className='flex flex-col gap-6 max-w-lg' onSubmit={async e => { await handleSubmit(e) }}>
      <div>
        <div className='text-xl font-semibold'>Reset Password</div>
        <div className='text-slate-500 font-light'>To reset your password, enter your email address.</div>
      </div>
      <Input
        id='email'
        testId='email'
        value={email}
        onChange={value => { setEmail(value ?? '') }}
        cleaner={(value?: string) => (value ?? '').trim().toLowerCase()}
        placeholder='Email'
      />
      <Button onClick={handleSubmit}>Send Reset Instructions</Button>
    </form>
  )
}
