import React from 'react'
import { useForm } from 'react-hook-form'
import {
  Container,
  Button,
  FormControl,
  FormLabel,
  Input,
  useColorModeValue, FormErrorMessage, useToast,
} from '@chakra-ui/react'
import agent from '../../api/agent'
import { IForgotPassword } from '../../models/user'

export default function ForgotPassword() {
  const bg = useColorModeValue('gray.50', 'transparent')
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting, isDirty },
  } = useForm()
  const toast = useToast()

  interface Message {
    success: boolean
    data: string
  }

  const onSubmit = handleSubmit(async (values) => {
    const message = await agent.Account.forgot(values as IForgotPassword) as Message
    toast({
      title: 'Email Sent',
      status: 'success',
      description: message.data,
      isClosable: true,
      duration: 10000,
      position: 'top'
    })
  })

  return (
    <Container style={{ marginTop: '7rem', paddingBottom: '5rem' }}>
      <form onSubmit={onSubmit}>
        <FormControl isInvalid={Boolean(errors.email)} mb={'3'}>
          <FormLabel htmlFor="email">Email</FormLabel>
          <Input
            id="email"
            bg={bg}
            _placeholder={{ color: 'gray.500' }}
            border="1px"
            borderColor="gray.500"
            rounded="md"
            placeholder="Email"
            {...register('email', {
              required: 'Email is required',
              pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            })}
          />
          <FormErrorMessage>
            {errors.email?.type === 'required' && errors.email.message?.toString()}
            {errors.email?.type === 'pattern' && 'Invalid Email Address'}
          </FormErrorMessage>
        </FormControl>
        <br/>
        <Button
          type="submit"
          disabled={!isDirty}
          isLoading={isSubmitting}
        >
          Submit
        </Button>
      </form>
    </Container>
  )
}
