import { capitalize } from 'lodash-es';
import React, { Fragment } from 'react';
import { Col, ControlLabel, FormControl, FormGroup } from 'react-bootstrap';
import FieldAlert from './FieldAlert';
import { useFormContext } from 'react-hook-form';
import RequiredStar from '../RequiredStar';

function TextFieldGroup(props) {
  const { register, errors } = useFormContext();
  const {
    type,
    name,
    label,
    layout,
    registerOptions = {},
    ...controlProps
  } = props;
  const controlId = `form${name}`;

  const unpackedName = name.split('.');
  const error = unpackedName.reduce(
    (acc, key) => (acc ? acc[key] : undefined),
    errors
  );
  const fieldLabel = label || capitalize(unpackedName.pop());

  const Wrapper = layout ? Col : Fragment;

  return (
    <FormGroup controlId={controlId}>
      <Wrapper {...(layout && layout.labelCol)}>
        <ControlLabel>
          {fieldLabel}
          {registerOptions.required && <RequiredStar />}
        </ControlLabel>
      </Wrapper>
      <Wrapper {...(layout && layout.fieldCol)}>
        <FormControl
          type={type}
          name={name}
          componentClass={type === 'textarea' ? 'textarea' : 'input'}
          inputRef={register(registerOptions)}
          {...controlProps}
        />
        {error && <FieldAlert fieldLabel={fieldLabel} error={error} />}
      </Wrapper>
    </FormGroup>
  );
}

export default TextFieldGroup;
