import { ViewIcon, ViewOffIcon } from '@chakra-ui/icons'
import {
  Button,
  FormControl,
  FormControlProps,
  FormErrorMessage,
  FormLabel,
  Input,
  InputGroup,
  InputLeftElement,
  InputRightElement,
  Text,
} from '@chakra-ui/react'
import Error from 'next/error'
import React, { useState } from 'react'
import { FieldErrors } from 'react-hook-form'

interface ICustomInputProps {
  name: string
  id?: string
  label?: string
  placeholder?: string
  type?: string
  // errors?: FieldErrors
  errors?: Error | FieldErrors
  disabled?: boolean
  register?: any
  leftElement?: JSX.Element
  rightElement?: JSX.Element
  fieldRequired?: boolean
}

const CustomInput: React.FunctionComponent<ICustomInputProps & FormControlProps> = (props) => {
  const {
    register,
    errors,
    label,
    id,
    name,
    type = 'text',
    placeholder,
    leftElement,
    rightElement,
    disabled = false,
    fieldRequired = false,
    ...rest
  } = props
  const error = errors[name]

  const [showPassword, setShowPassword] = useState(false)
  console.log('🚀 ~ file: index.tsx ~ line 51 ~ showPassword', type)

  return (
    <FormControl isInvalid={!!error} px={'2px'} {...rest}>
      <FormLabel display={'flex'} htmlFor={name} mb="16px" color={'primary'} style={{ gap: '4px' }}>
        {label} {fieldRequired && <Text color={'red.500'}>*</Text>}
      </FormLabel>
      <InputGroup>
        {leftElement && <InputLeftElement>{leftElement}</InputLeftElement>}
        <Input
          id={name}
          placeholder={placeholder}
          type={showPassword ? 'text' : type}
          {...register(name)}
          variant={'primary'}
        />
        {rightElement && <InputRightElement>{rightElement}</InputRightElement>}
        {type === 'password' && (
          <InputRightElement width="4.5rem">
            <Button variant={'unstyled'} onClick={() => setShowPassword((showPassword) => !showPassword)}>
              {showPassword ? <ViewIcon /> : <ViewOffIcon />}
            </Button>
          </InputRightElement>
        )}
      </InputGroup>
      {error && <FormErrorMessage color="#FF4B32">{error?.message}</FormErrorMessage>}
    </FormControl>
  )
}

export default CustomInput
