import React from 'react';
import cx from 'classnames';
import { ListView, useListViewApi } from '../listView';
import type { ListBoxProps } from './types';
import type { ListViewItem, ListViewValue } from '../listView';

const CLASS_NAME = 'SuiteListBox';

/**
 * ListBox is used for collecting user provided information from a list of options. This component is what powers our single select dropdown and allows for one single item to be selected from a list of options.
 *
 * @type molecule
 * @status live
 * @tags tables-lists
 */
export function ListBox<T extends ListViewItem, M extends boolean = false>({
    className,
    style,
    initialValue,
    onChange,
    onLoadOptions,
    optionsMatchBy,
    options = [],
    testId = CLASS_NAME,
    selectedValue,
    width,
    bordered,
    shadowed,
    multi,
    ...rest
}: ListBoxProps<T, M>) {
    const { variant } = rest;
    const defaultValue = (multi ? [] : undefined) as ListViewValue<T, M>;

    const { props } = useListViewApi<T, M>({
        onLoadOptions,
        onChange,
        options,
        initialValue,
        defaultValue,
        selectedValue,
        optionsMatchBy,
        staticMode: variant === 'static',
    });

    return (
        <div
            className={cx(CLASS_NAME, className, { bordered }, { shadowed })}
            data-testid={testId}
            style={{ width, ...style }}
        >
            <ListView {...rest} {...props} />
        </div>
    );
}
