import React, { useRef } from 'react'
import { useForm } from 'react-hook-form'
import { UserFormValues } from '../../models/user'
import { createUser } from '../../stateManagement/userState'
import {
  Alert,
  AlertDescription,
  AlertIcon,
  Button,
  Container,
  FormControl, FormErrorMessage,
  FormLabel,
  Input, useColorModeValue,
} from '@chakra-ui/react'

export default function CreateUser() {
  const {
    register,
    handleSubmit,
    setError,
    watch,
    formState: { errors, isSubmitting, isDirty },
  } = useForm()
  const password = useRef({})
  password.current = watch('password', '')

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

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

  return (
    <Container style={{ marginTop: '7rem', paddingBottom: '5rem' }}>
      <form onSubmit={onSubmit}>
        <FormControl isInvalid={Boolean(errors.name)} mb={'3'}>
          <FormLabel htmlFor='name'>Full Name</FormLabel>
          <Input
            id='name'
            bg={bg}
            _placeholder={{ color: 'gray.500' }}
            border="1px"
            borderColor="gray.500"
            rounded="md"
            placeholder='Full Name'
            {...register('name', { required: 'Name is required' })}
          />
          {errors.name && <FormErrorMessage>{ errors.name.message?.toString()}</FormErrorMessage>}
        </FormControl>
        <FormControl isInvalid={Boolean(errors.displayName)} mb={'3'}>
          <FormLabel htmlFor='displayName'>Display Name</FormLabel>
          <Input
            id='displayName'
            bg={bg}
            _placeholder={{ color: 'gray.500' }}
            
            border="1px"
            borderColor="gray.500"
            rounded="md"
            placeholder='Display Name'
            {...register('displayName', { required: 'Display Name is required' })}
          />
          {errors.displayName && <FormErrorMessage>{ errors.displayName.message?.toString()}</FormErrorMessage>}
        </FormControl>
        <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' })}
          />
          {errors.email && <FormErrorMessage>{ errors.email.message?.toString()}</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',
              minLength: {
                value: 8,
                message: 'Password must have at least 8 characters',
              },
            })}
          />
          {errors.password && <FormErrorMessage>{ errors.password.message?.toString()}</FormErrorMessage>}
        </FormControl>
        {errors.password && (
          <>
            <Alert status='error' style={{ marginBottom: 10 }}>
              <AlertIcon />
              <AlertDescription>{errors.password.message?.toString()}</AlertDescription>
              {/*<CloseButton position='absolute' right='8px' top='8px' />*/}
            </Alert>
            <br />
          </>
        )}
          <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',
            })}
          />
            {errors.repeat_password && <FormErrorMessage>{ errors.repeat_password.message?.toString()}</FormErrorMessage>}
        </FormControl>
        {errors.repeat_password && (
          <>
            <Alert status='error' style={{ marginBottom: 10 }}>
              <AlertIcon />
              <AlertDescription>{errors.repeat_password.message?.toString()}</AlertDescription>
              {/*<CloseButton position='absolute' right='8px' top='8px' />*/}
            </Alert>
          </>
        )}
        <br />
        <Button
          type='submit'
          disabled={!isDirty}
          isLoading={isSubmitting}
        >
          Submit
        </Button>
      </form>
    </Container>
  )
}
