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

interface Message {
  success: boolean
  data: string
}

interface URL {
  token: string
}

export default function ResetPassword() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isSubmitting, isDirty },
  } = useForm()
  const { token } = useParams<URL>()
  const history = useNavigate()
  const toast = useToast()
  const password = useRef({})
  password.current = watch('password', '')

  const onSubmit = handleSubmit(async (data) => {
    const message = await agent.Account.reset(token, data as IResetPassword) as Message
    if (message.success) {
      setTimeout(() => history('/login'), 3000)
      toast({
        title: 'Password Reset',
        status: 'success',
        description: 'Your password has been reset. You will be redirected to login automatically',
        isClosable: true,
        duration: 5000,
        position: 'top',
      })
    } else {
      toast({
        title: 'Password Not Reset',
        status: 'error',
        description: 'Something went wrong, please contact the website administrator',
        isClosable: true,
        duration: 10000,
        position: 'top',
      })
    }
  })

  const bg = useColorModeValue('gray.50', 'transparent')

  return (
    <Container style={{ marginTop: '7rem', paddingBottom: '5rem' }}>
      <form onSubmit={onSubmit}>
        <FormControl isInvalid={Boolean(errors.password)} mb={'3'}>
          <FormLabel htmlFor="password">Password</FormLabel>
          <Input
            id="password"
            bg={bg}
            _placeholder={{ color: 'gray.500' }}

            border="1px"
            borderColor="gray.500"
            rounded="md"
            placeholder="Password"
            type="password"
            {...register('password', {
              required: 'You must specify a password',
              minLength: {
                value: 8,
                message: 'Password must have at least 8 characters',
              },
            })}
          />
          <FormErrorMessage>
            {errors.password && errors.password.message?.toString()}
          </FormErrorMessage>
        </FormControl>
        <FormControl isInvalid={Boolean(errors.repeat_password)} mb={'3'}>
          <FormLabel htmlFor="repeat_password">Repeat Password</FormLabel>
          <Input
            id="repeat_password"
            bg={bg}
            _placeholder={{ color: 'gray.500' }}
            border="1px"
            borderColor="gray.500"
            rounded="md"
            placeholder="Repeat Password"
            type="password"
            {...register('repeat_password', {
              validate: (value) =>
                value === password.current || 'The passwords do not match',
            })}
          />
          <FormErrorMessage>
            {errors.repeat_password && errors.repeat_password.message?.toString()}
          </FormErrorMessage>
        </FormControl>
        <br/>
        <Button
          type="submit"
          disabled={!isDirty}
          isLoading={isSubmitting}
        >
          Submit
        </Button>
      </form>
    </Container>
  )
}
