import React, { useState, type ReactElement } from 'react'
"use client";
import Button from '@/Components/Buttons/Button'
import Input from '@/Components/Inputs/Input'
import InputError from '@/Components/Errors/InputError/InputError'
import AuthApi from '@/Components/Auth/AuthApi'
import { useForm } from 'react-hook-form'
import Utilities from '@/Components/Auth/Utilities'

interface IResetPassword {
  password?: string
  confirmPassword?: string
  oneTimePassword?: string
  onSuccess?: () => void
  onFailure?: () => void
}

interface IResetPasswordForm {
  password: string
  confirmPassword: string
}

export default function ResetPassword({
  oneTimePassword,
  onSuccess,
  onFailure
}: IResetPassword): ReactElement {
  const [loading, setLoading] = useState(false)
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm<IResetPasswordForm>()

  const onSubmit = async (data: IResetPasswordForm): Promise<void> => {
    if (loading) return
    try {
      setLoading(true)
      const response = await AuthApi.resetPassword(data.password, oneTimePassword ?? '')
      console.log(response.data)
      setLoading(false)
      onSuccess?.()
    } catch (error) {
      console.error(error)
      setLoading(false)
      onFailure?.()
    }
  }

  return (
    <div>
      <div className='flex flex-col gap-4 max-w-lg'>
        <div>
          <div className='text-xl font-semibold'>Create a New Password</div>
          <div className='text-slate-500 font-light'>Enter a new password below.</div>
        </div>
        <form onSubmit={handleSubmit(onSubmit)} className='flex flex-col gap-4 max-w-lg'>
          <div>
            <Input
              id='password'
              testId='password'
              placeholder='Password'
              validator={register('password', Utilities.PasswordConstraints)}
              type='password'
            />
            <InputError
              fieldError={errors.password}
              errorMessages={Utilities.PasswordErrorMessages}
            />
          </div>
          <div>
            <Input
              id='confirmPassword'
              testId='confirmPassword'
              placeholder='Confirm Password'
              validator={register('confirmPassword', {
                required: true,
                validate: {
                  passwordsMatch: (value: string) => value === watch('password')
                }
              })}
              type='password'
            />
            <InputError
              fieldError={errors.confirmPassword}
              errorMessages={{
                passwordsMatch: 'Passwords do not match.'
              }}
            />
          </div>
          <Button onClick={handleSubmit(onSubmit)} disabled={loading}>Sign Up</Button>
        </form>
      </div>
    </div>
  )
}
