import React from 'react';
import { buildClassName } from '../../shared/utils/class-util';
import { compact } from 'lodash';

interface LabeledSelectProps {
  name: string;
  id?: string;
  required?: boolean;
  value?: string | number;
  defaultValue?: string | number;
  label?: string;
  hasError?: boolean;
  extraClassName?: string;
  extraDropdownClassName?: string;
  options?: {
    key: string;
    value: string | number | undefined;
    label: string;
  }[];
  onChange?: React.ChangeEventHandler<HTMLSelectElement>;
  onBlur?: React.FocusEventHandler<HTMLSelectElement>;
}

const LabeledSelect: React.FC<LabeledSelectProps> = ({
  name,
  id,
  required,
  value,
  defaultValue,
  label,
  extraClassName,
  extraDropdownClassName,
  hasError,
  options,
  onChange,
  onBlur
}) => {
  return (
    <label className={buildClassName(['form__group', extraClassName, hasError && 'form__group--error'])}>
      <span className="form__label">{compact([label, required && '*']).join(' ')}</span>
      <div className={buildClassName(['dropdown', extraDropdownClassName])}>
        <select name={name} id={id} defaultValue={defaultValue} value={value} onBlur={onBlur} onChange={onChange}>
          {options?.map((option) => (
            <option key={option.key} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>
    </label>
  );
};

export default LabeledSelect;
