import React, { useEffect, useState } from 'react';
import { Dropdown } from '@theorchard/suite-components';
import { map } from 'lodash-es';
import { useRunControllerList } from 'src/apollo/queries/run-controller';
import { getSelectedOptions } from 'src/utils/searchable-dropdown-option';

export interface RunControllerSelectPropTypes {
    accountId?: string;
    className?: string;
    contractType: string;
    disabled?: boolean;
    onChange: (val: any) => void;
    testId?: string;
    value: string;
}

export const RunControllerSelect: React.FC<RunControllerSelectPropTypes> = ({
    accountId,
    className,
    contractType,
    disabled = false,
    onChange,
    testId,
    value,
}) => {
    const [runControllers, setRunControllers] = useState<any[]>([]);
    const [runControllersLimit, setRunControllersLimit] = useState<number>(100);
    const { data, loading, refetch } = useRunControllerList({
        limit: runControllersLimit,
        offset: 0,
        contractType,
        accountId,
    });

    useEffect(() => {
        refetch();
    }, [runControllersLimit]);

    useEffect(() => {
        if (data) {
            const runControllersCount: number =
                data?.abacusRunControllers?.totalCount || 0;
            if (runControllersCount > runControllersLimit)
                return setRunControllersLimit(runControllersCount);
            const items = map(data?.abacusRunControllers?.items, row => ({
                label: row?.runControllerName,
                value: row?.runControllerId,
            }));
            setRunControllers(items);
        }
    }, [data, accountId, contractType]);

    return (
        <Dropdown
            className={className || 'RunControllerSelect'}
            id="runControllerSelect"
            isClearable={false}
            isDisabled={disabled}
            isMulti={false}
            name="runControllerSelect"
            onChange={onChange}
            options={contractType ? runControllers : []}
            value={getSelectedOptions(runControllers, value)}
            placeholder="Choose... "
            testId={testId}
            isLoading={loading}
        />
    );
};

export default RunControllerSelect;
