import React, { useEffect, useState } from 'react';
import { MultiSelect } from '@theorchard/suite-components';
import { map } from 'lodash-es';
import { useRunControllerList } from 'src/apollo/queries/run-controller';
import type { ListViewItem } from '@theorchard/suite-components';

const RUN_CONTROLLER_PLACEHOLDER = 'Run Controller';

export interface RunControllerSelectPropTypes {
    className?: string;
    compact?: boolean;
    isDisabled?: boolean;
    fieldTextMaxWidth?: number;
    menuMaxWidth?: number;
    onChange: (e: ListViewItem[] | undefined) => void;
    placeholder?: string;
    value?: string[];
}

const RunControllerMultiSelect: React.FC<RunControllerSelectPropTypes> = ({
    className = '',
    compact = false,
    isDisabled = false,
    menuMaxWidth,
    onChange,
    placeholder = RUN_CONTROLLER_PLACEHOLDER,
    value,
}) => {
    const [runControllers, setRunControllers] = useState<ListViewItem[]>([]);
    const { data, loading } = useRunControllerList({
        limit: 500,
        offset: 0,
    });

    useEffect(() => {
        if (data && !loading) {
            const items = map(data?.abacusRunControllers?.items, row => ({
                label: row?.runControllerName ?? '',
                value: row?.runControllerId?.toString() ?? '',
            }));
            setRunControllers(items);
        }
    }, [data, loading]);

    return (
        <MultiSelect
            className={`SelectRunController ${className}`}
            disabled={isDisabled}
            id="runControllerSelect"
            testId="runControllerSelect"
            requireApply
            menuMaxWidth={menuMaxWidth}
            onChange={onChange}
            options={runControllers}
            placeholder={placeholder}
            selectedValue={
                (!loading &&
                    runControllers.filter((item: ListViewItem) =>
                        value?.includes(item.value)
                    )) ||
                []
            }
            components={{
                OptionLabel: ({ option }) => (
                    <div className="runControllerSelectText">
                        {option.label}
                    </div>
                ),
            }}
            compact={compact}
        />
    );
};

export default RunControllerMultiSelect;
