import React from 'react'
import { useForm } from 'react-hook-form'
import { UserFormValues } from '../../models/user'
import { login } from '../../stateManagement/userState'
import {
  Container,
  Button,
  FormControl,
  FormLabel,
  Input,
  useColorModeValue, HStack, Center, FormErrorMessage,
} from '@chakra-ui/react'
import { Link } from 'react-router-dom'

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

  const onSubmit = handleSubmit(async (data) =>
    await login(data as UserFormValues).catch(() =>
      [
        {
          type: 'server',
          name: 'password',
          message: 'Invalid Email or Password',
        },
      ].forEach(({ name, type, message }) => {
        setError(name, { type, message })
      }),
    ),
  )

  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>
        <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' })}
          />
          <FormErrorMessage>
            {errors.password && errors.password.message?.toString()}
          </FormErrorMessage>
        </FormControl>
        <br/>
        <HStack>
          <Button
            type="submit"
            disabled={!isDirty}
            isLoading={isSubmitting}
          >
            Submit
          </Button>
        </HStack>
        <Center mt={'5rem'}>
          <Button as={Link} to={'/forgotpassword'}>Forgot Password</Button>
        </Center>
      </form>
    </Container>
  )
}
