import React, { useEffect, useState } from 'react';
import { MultiSelect } from '@theorchard/suite-components';
import SelectTruncatedText from 'src/components/shared/select-truncated-text';
import type { ListViewItem } from '@theorchard/suite-components';
import type { AbacusContractList } from 'src/types/abacus-contract';

const FILTER_PLACEHOLDER = 'Search by Contract Name or ID';

const SEARCH_PLACEHOLDER = 'Contract';

export interface AccountContractsSelectPropTypes {
    accountContracts: Partial<AbacusContractList>[] | [];
    className?: string;
    compact?: boolean;
    isDisabled?: boolean;
    menuMaxWidth?: number;
    onChange: (e: ListViewItem[] | undefined) => void;
    truncatedTextMaxWidth: number;
    value?: string[] | [];
}

export const AccountContractsSelect: React.FC<
    AccountContractsSelectPropTypes
> = ({
    accountContracts,
    className = '',
    compact = false,
    isDisabled = false,
    menuMaxWidth,
    onChange,
    truncatedTextMaxWidth,
    value,
}) => {
    const [contracts, setContracts] = useState<ListViewItem[]>([]);

    useEffect(() => {
        const options: ListViewItem[] = [];

        accountContracts.forEach(({ contractId, contractName }) => {
            options.push({
                label: `${contractName} (ID ${contractId})`,
                value: contractId!,
            });
        });
        options.sort((a, b) => a.label!.localeCompare(b.label!));
        setContracts(options);
    }, []);

    return (
        <MultiSelect
            className={`SelectAccountContract ${className}`}
            disabled={isDisabled}
            id="accountContract"
            filterPlaceholder={FILTER_PLACEHOLDER}
            menuMaxWidth={menuMaxWidth}
            onChange={onChange}
            options={contracts}
            optionTagMaxWidth={truncatedTextMaxWidth}
            placeholder={SEARCH_PLACEHOLDER}
            requireApply
            selectedValue={value}
            components={{
                OptionLabel: ({ option }) => (
                    <SelectTruncatedText
                        text={option.label || ''}
                        placement="right"
                        maxWidth={truncatedTextMaxWidth}
                    />
                ),
            }}
            compact={compact}
            portalElement={document.body}
        />
    );
};

export default AccountContractsSelect;
