import type { ComponentChildren, JSX } from 'preact';
import { Field } from '../core/Field';
import { cn } from '../core/cn';
import type { SelectOption } from '../core/Select';

export type MultiSelectFieldProps = Omit<JSX.SelectHTMLAttributes<HTMLSelectElement>, 'value' | 'onChange' | 'multiple'> & {
  label?: string;
  hint?: string;
  right?: ComponentChildren;
  options: SelectOption[];
  value?: string[];
  fieldClassName?: string;
  selectClassName?: string;
  onValueChange?: (value: string[]) => void;
};

export function MultiSelectField({
  label,
  hint,
  right,
  options,
  value,
  fieldClassName,
  selectClassName,
  onValueChange,
  required,
  'aria-label': ariaLabel,
  ...props
}: MultiSelectFieldProps) {
  return (
    <Field label={label} hint={hint} right={right as any} required={Boolean(required)} className={fieldClassName}>
      <select
        {...props}
        required={required}
        aria-label={ariaLabel ?? label}
        aria-required={required ? true : undefined}
        multiple
        value={(value ?? []) as any}
        className={cn('ask-theme-select ask-w-full ask-min-h-20 ask-rounded-xl ask-border ask-p-2 ask-text-[12px]', selectClassName)}
        onChange={(event: any) => {
          const next = Array.from(event?.currentTarget?.selectedOptions ?? []).map((option: any) => String(option?.value ?? ''));
          onValueChange?.(next.filter(Boolean));
        }}
      >
        {options.map((option) => (
          <option key={option.value} value={option.value} disabled={option.disabled}>
            {option.label}
          </option>
        ))}
      </select>
    </Field>
  );
}
