import React from 'react';
import { Dropdown } from '@theorchard/suite-components';
import { map } from 'lodash-es';
import { useReferencePaymentEntities } from 'src/apollo/queries/reference-payment-entity';
import { getSelectedOptions } from 'src/utils/searchable-dropdown-option';
import type { DropdownOption } from '@theorchard/suite-components';

export interface PaymentEntitySelectPropTypes {
    className?: string;
    isClearable?: boolean;
    isDisabled?: boolean;
    id: string;
    isMultiSelect?: boolean;
    onChange: any;
    name: string;
    placeholder?: string;
    value: string | undefined | [];
}

export const PaymentEntitySelect: React.FC<PaymentEntitySelectPropTypes> = ({
    className = '',
    isClearable = true,
    isDisabled = false,
    id,
    isMultiSelect = false,
    name,
    onChange,
    placeholder = '',
    value,
}) => {
    const { data: paymentEntities, loading } = useReferencePaymentEntities();
    let paymentEntitiesOptions: DropdownOption[] = [];

    if (
        paymentEntities &&
        paymentEntities.abacusReferencePaymentEntities.items
    ) {
        const { items } = paymentEntities.abacusReferencePaymentEntities;
        paymentEntitiesOptions = map(
            items,
            ({ referencePaymentEntityId, paymentEntityName }: any) => ({
                value: referencePaymentEntityId.toString(),
                label: paymentEntityName,
            })
        );
    }

    return (
        <>
            <Dropdown
                className={`SelectPaymentEntity ${className}`}
                closeMenuOnSelect={!isMultiSelect}
                id={id}
                isClearable={isClearable}
                isDisabled={isDisabled}
                isMulti={isMultiSelect}
                name={name}
                onChange={onChange}
                options={paymentEntitiesOptions}
                value={getSelectedOptions(paymentEntitiesOptions, value)}
                placeholder={placeholder}
                isLoading={loading}
            />
        </>
    );
};

export default PaymentEntitySelect;
