import Form from 'react-bootstrap/Form';

function FormSelect(props) {
  const {
    input,
    required,
    horizontal,
    label,
    placeholder,
    options,
    multiple,
    size,
    meta: { touched, error }
  } = props;
  const id = props.id || input.name;
  const value = multiple && !input.value ? [] : input.value;
  const exactLabel = ['.', '?', '!', '؟'].includes(label.charAt(label.length - 1));

  if (horizontal) {
    return (
      <Form.Group controlId={id} className='d-flex align-items-baseline'>
        <Form.Label className='mr-3 flex-shrink-0'>
          {exactLabel ? label : `${label} :`}
          {required && <span className='text-danger'> * </span>}
        </Form.Label>
        <div className='flex-grow-1'>
          <Form.Control
            {...input}
            custom
            required={required}
            value={value}
            placeholder={placeholder}
            options={options}
            size={size}
            as='select'
            isValid={!!value}
          >
            {options.map(({ value, text, key }) => (
              <option key={key} value={value}>
                {text}
              </option>
            ))}
          </Form.Control>
          {touched && error != null && <Form.Text className='text-danger'>{error}</Form.Text>}
        </div>
      </Form.Group>
    );
  }

  return (
    <Form.Group controlId={id}>
      <Form.Label>
        {exactLabel ? label : `${label} :`}
        {required && <span className='text-danger'> * </span>}
      </Form.Label>
      <Form.Control
        {...input}
        required={required}
        value={value}
        placeholder={placeholder}
        options={options}
        size={size}
        as='select'
      >
        {options.map(({ value, text, key }) => (
          <option key={key} value={value}>
            {text}
          </option>
        ))}
      </Form.Control>
      {touched && error != null && <Form.Text className='text-danger'>{error}</Form.Text>}
    </Form.Group>
  );
}

FormSelect.defaultProps = {
  exactLabel: false,
  placeholder: 'انتخاب کنید...',
  options: []
};

export default FormSelect;
