import type { FC } from 'react';
import React, { useCallback } from 'react';
import { Select, type SelectOption } from '@theorchard/suite-components';
import { BrandIcon } from '@theorchard/suite-icons';
import {
    useAccountsXppQuery,
    useAccountXppSearchQuery,
    type AccountXpp,
} from 'src/data/queries/accountsXpp';

export interface PpAccountSearchDropdownProps {
    menuWidth?: string;
    placeholder: string;
    className: string;
    onSelect: (option: SelectOption | undefined) => void;
    options?: SelectOption[];
}

const createOption = (account: AccountXpp): SelectOption =>
    ({
        label: `${account.name} • ${account.vendorId}`,
        value: account.vendorId.toString(),
    } as SelectOption);

const PpAccountSearchDropdown: FC<PpAccountSearchDropdownProps> = props => {
    const { className, menuWidth, placeholder, onSelect, options } = props;
    const { data: accountsData } = useAccountsXppQuery(!!options);
    const [executeSearch] = useAccountXppSearchQuery();

    const onLoadOptionsHandler = useCallback(
        async (term?: string) => {
            if (term) {
                const searchAccountsData = await executeSearch({
                    variables: { term },
                });
                return {
                    data: searchAccountsData?.length
                        ? searchAccountsData.map(createOption)
                        : [],
                };
            }
            return {};
        },
        [executeSearch]
    );

    return (
        <Select
            className={className}
            menuWidth={menuWidth}
            placeholder={placeholder}
            onSelect={onSelect}
            onLoadOptions={options ? undefined : onLoadOptionsHandler}
            options={options ?? accountsData?.map(createOption)}
            components={{
                // Use custom OptionLabel instead of icon key in SelectOption dict
                // so that the icon does not show when the option is selected
                OptionLabel: ({ option }) => (
                    <div>
                        <BrandIcon brand="orchard" size="16" />
                        <span
                            className="SuiteListView-option-label"
                            style={{
                                verticalAlign: 'middle',
                                marginLeft: '5px',
                            }}
                        >
                            {option?.label}
                        </span>
                    </div>
                ),
            }}
        />
    );
};

export default PpAccountSearchDropdown;
