import React from 'react';
import cx from 'classnames';
import { SelectDropdown, SelectInput as SelectInputDefault } from './components';
import { CLASSNAME } from './constants';
import { t } from './i18n';
import type { SelectOption, SelectProps } from './types';

/**
 * Select components are used for collecting user provided information from a list of options. This component is a single select, and allows for one single item to be selected from a list of options.
 *
 * @type molecule
 * @status live
 * @tags form-elements, selects
 */
export function Select<T extends SelectOption = SelectOption>({
    name,
    placeholder = t('selectValue'),
    disabled,
    className,
    testId = CLASSNAME,
    defaultValue = undefined,
    compact,
    fieldTextMaxWidth,
    hideClearButton,
    components,
    onSerializeValue,
    controlId,
    onFocus,
    onBlur,
    showSelectedSubtitle,
    showExcludeMode,
    showExcludeModeToggle = showExcludeMode,
    excludeMode,
    excludeModeText,
    error,
    ...props
}: SelectProps<T>) {
    const { SelectInput = SelectInputDefault } = components ?? {};
    return (
        <SelectDropdown<T, false>
            {...props}
            testId={testId}
            className={cx(CLASSNAME, className)}
            disabled={disabled}
            defaultValue={defaultValue}
            components={components}
            excludeMode={excludeMode}
            excludeModeText={excludeModeText}
            showExcludeModeToggle={showExcludeModeToggle}
        >
            {({ selectedValue, defaultValue, menuOpen, onKeyDown, onClear }) => (
                <SelectInput
                    id={controlId}
                    name={name}
                    disabled={disabled}
                    error={error}
                    menuOpen={menuOpen}
                    value={selectedValue}
                    defaultValue={defaultValue}
                    placeholder={placeholder}
                    onKeyDown={onKeyDown}
                    onClear={onClear}
                    onFocus={onFocus}
                    onBlur={onBlur}
                    showSelectedSubtitle={showSelectedSubtitle}
                    variant={compact ? 'compact' : undefined}
                    fieldTextMaxWidth={fieldTextMaxWidth}
                    hideClearButton={hideClearButton}
                    components={components}
                    onSerializeValue={onSerializeValue}
                    excludeMode={excludeMode}
                    excludeModeText={excludeModeText}
                />
            )}
        </SelectDropdown>
    );
}
