import React from 'react';
import { Dropdown } from '@theorchard/suite-components';
import { useReferencePaymentTypes } from 'src/apollo/queries/reference-payment-types';
import { REFERENCE_PAYMENT_TYPE_ID, USER_FEATURES } from 'src/constants';
import { isFeatureFlagEnabled } from 'src/utils/feature-flag';

export interface ReferencePaymentTypeSelectPropTypes {
    className?: string;
    isClearable?: boolean;
    isDisabled?: boolean;
    id: string;
    isMultiSelect?: boolean;
    onChange: any;
    name: string;
    placeholder?: string;
    value: { label: string; value: string };
}

export const ReferencePaymentTypeSelect: React.FC<
    ReferencePaymentTypeSelectPropTypes
> = ({
    className = '',
    isClearable = false,
    isDisabled = false,
    id,
    isMultiSelect = false,
    name,
    onChange,
    placeholder = '',
    value,
}) => {
    const isFeatureAllowAllocatedFunds = isFeatureFlagEnabled(
        USER_FEATURES.ABACUS_ALLOW_ALLOCATED_FUNDS
    );

    const { data: referencePaymentTypes, loading } = useReferencePaymentTypes();

    let referencePaymentTypesOptions =
        referencePaymentTypes?.abacusReferencePaymentTypes.items.map(item => ({
            label: item.notes || '',
            value: item.referencePaymentTypeId,
        })) || [];

    if (!isFeatureAllowAllocatedFunds) {
        referencePaymentTypesOptions = referencePaymentTypesOptions.filter(
            option => option.value !== REFERENCE_PAYMENT_TYPE_ID.ALLOCATED_FUNDS
        );
    }

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

export default ReferencePaymentTypeSelect;
