import React from 'react'

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

import {
  Container,
  Label,
  Content,
  ErrorMessage,
  SwitchFill,
  Row,
} from './styles'

interface SwitchProps {
  label?: string | JSX.Element
  control: Control<any>
  name: string
}

const Switch: React.FC<SwitchProps> = ({ control, name, label }) => {
  return (
    <Controller
      name={name}
      control={control}
      defaultValue={false}
      render={({ field: { onChange, value }, formState: { errors } }) => (
        <Container>
          <Row>
            {label && <Label>{label}</Label>}
            <Content active={value} onPress={() => onChange(!value)}>
              <SwitchFill />
            </Content>
          </Row>

          {errors[name] && <ErrorMessage>{errors[name].message}</ErrorMessage>}
        </Container>
      )}
    />
  )
}

export default Switch
