import React, { type FC } from 'react';
import { Dropdown } from '@theorchard/suite-components';
import cx from 'classnames';
import './styles.scss';
import TruncatedText from '../truncatedText';
import type {
    DropdownOption,
    DropdownProps,
} from '@theorchard/suite-components';
import type { FilterOption } from 'src/data/queries/reviewQueueSearch/types';

interface SetParamsCallback {
    (name: string, value: string): void;
}

export type ParamValue = string | number | (string | number)[];

type FormatOptionFunction = DropdownProps<DropdownOption>['formatOptionLabel'];

export interface Props extends Omit<DropdownProps, 'options'> {
    filterName: string;
    onFilterChange: SetParamsCallback;
    filterOptions?: FilterOption[];
}

export const CLASS_NAME = 'DropdownFilter';

const DropdownFilter: FC<Props> = ({
    className,
    filterName,
    filterOptions,
    onFilterChange,
    ...props
}) => {
    const handleDropdownFilterSelection = (
        name: string,
        value: string | undefined
    ) => {
        onFilterChange(filterName, value ?? '');
    };

    const formatOptionLabel: FormatOptionFunction = (option, { context }) => (
        <div className="LabelFilterName">
            <TruncatedText
                value={option.label}
                placement={context === 'value' ? 'bottom' : 'right'}
            />
        </div>
    );

    const options = filterOptions?.map(({ id, name }) => ({
        label: name ?? '',
        value: id,
    }));

    return (
        <Dropdown
            {...props}
            name={filterName}
            className={cx(CLASS_NAME, className)}
            isClearable
            onValueChanged={handleDropdownFilterSelection}
            options={options}
            formatOptionLabel={formatOptionLabel}
        />
    );
};

export default DropdownFilter;
