import type { SelectHTMLAttributes } from 'react';
import { Champ, CLASSES_CHAMP, type ChampCommun } from './Champ';
import { cx } from './cx';

export interface SelectOption {
  value: string;
  label: string;
}

export interface SelectProps
  extends
    ChampCommun,
    Omit<
      SelectHTMLAttributes<HTMLSelectElement>,
      'aria-describedby' | 'aria-invalid' | 'children'
    > {
  options: readonly SelectOption[];
  /** Première option vide, par exemple « Choisir une ville ». */
  placeholder?: string;
}

export function Select({
  id,
  label,
  hint,
  error,
  requiredLabel,
  required,
  options,
  placeholder,
  className,
  ...props
}: SelectProps) {
  return (
    <Champ
      id={id}
      label={label}
      hint={hint}
      error={error}
      required={required}
      requiredLabel={requiredLabel}
    >
      {(attributs) => (
        <select
          {...props}
          {...attributs}
          required={required}
          className={cx(CLASSES_CHAMP, className)}
        >
          {placeholder ? <option value="">{placeholder}</option> : null}
          {options.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      )}
    </Champ>
  );
}
