import type { FC } from 'react';
import React, { useCallback } from 'react';
import { Dropdown } from '@theorchard/suite-components';
import { orderBy, uniqBy } from 'lodash';
import type { DropdownOption } from 'src/types';

const CLASSNAME = 'AccountNameDropdown';

export interface DropDownAccountItem {
    name: string;
    id: string;
}

const createOption = (
    account: DropDownAccountItem
): DropdownOption<DropDownAccountItem> => ({
    label: account.name,
    value: account.id,
    data: account,
});

interface Props {
    selectedAccount?: string;
    accounts: DropDownAccountItem[];
    loading: boolean;
    onChange: (account?: string) => void;
    placeholder: string;
}

const AccountNameDropdown: FC<Props> = ({
    selectedAccount,
    accounts,
    loading,
    onChange,
    placeholder,
}) => {
    const deduplicateAccounts = uniqBy(accounts, 'id');
    const options = orderBy(
        [...deduplicateAccounts.map(createOption)],
        ['label'],
        ['asc']
    );
    const handleChange = useCallback(
        (value: DropdownOption<DropDownAccountItem> | null) => {
            onChange(value?.data?.id ?? undefined);
        },
        [onChange]
    );

    return (
        <Dropdown
            className={CLASSNAME}
            options={options}
            isLoading={loading}
            selectedValue={selectedAccount}
            onChange={handleChange}
            placeholder={placeholder}
            isClearable
        />
    );
};

export default AccountNameDropdown;
