import React, { useState } from 'react'
import { TextInputProps } from 'react-native'

import { Control, Controller, FieldError } from 'react-hook-form'

import {
  ButtonIcon,
  CalendarIcon,
  Container,
  ErrorMessage,
  InputContainer,
  Label,
  InputText,
  EyeOffIcon,
  EyeIcon,
} from './styles'
import { MaskProps, maskAnything } from '~/utils/masks'

interface InputProps extends TextInputProps {
  label?: string
  control: Control<any>
  name: string
  mask?: MaskProps
}

const Input: React.FC<InputProps> = ({
  control,
  name,
  label,
  secureTextEntry,
  mask,
  ...rest
}) => {
  const [showPassword, setShowPassword] = useState(false)

  const insertMask = (text: string, onChange: any) => {
    if (!mask) return onChange(text)
    return onChange(maskAnything(mask, text))
  }

  return (
    <Container>
      <Controller
        name={name}
        control={control}
        render={({
          field: { onChange, value, name },
          formState: { errors },
        }) => (
          <>
            {label && <Label>{label}</Label>}
            <InputContainer>
              <InputText
                value={value}
                onChangeText={text => insertMask(text, onChange)}
                secureTextEntry={secureTextEntry && !showPassword}
                autoCapitalize="none"
                {...rest}
              />
              {secureTextEntry && (
                <ButtonIcon onPress={() => setShowPassword(p => !p)}>
                  {showPassword ? <EyeIcon /> : <EyeOffIcon />}
                </ButtonIcon>
              )}
              {name === 'birthdate' && (
                <ButtonIcon>
                  <CalendarIcon />
                </ButtonIcon>
              )}
            </InputContainer>
            {errors[name] && (
              <ErrorMessage>{errors[name].message}</ErrorMessage>
            )}
          </>
        )}
      />
    </Container>
  )
}

export default Input
