import React from 'react';
import { MultiSelect } from '@theorchard/suite-components';
import type { ListViewItem } from '@theorchard/suite-components';
import { map } from 'lodash-es';
import { useReferencePaymentEntities } from 'src/apollo/queries/reference-payment-entity';

const SEARCH_PLACEHOLDER = 'Select Paid By(s)';

export interface PaymentEntityMultiSelectPropTypes {
    className?: string;
    compact?: boolean;
    isDisabled?: boolean;
    menuMaxWidth?: number;
    menuMinWidth?: string;
    onChange: (e: ListViewItem[] | undefined) => void;
    requireApply?: boolean;
    value?: ListViewItem[] | [];
}

export const PaymentEntityMultiSelect: React.FC<
    PaymentEntityMultiSelectPropTypes
> = ({
    className = '',
    compact = false,
    isDisabled = false,
    menuMaxWidth,
    menuMinWidth,
    onChange,
    requireApply = false,
    value,
}) => {
    const { data: paymentEntitiesData, loading: paymentEntitiesLoading } =
        useReferencePaymentEntities();

    const paymentEntitiesOptions: ListViewItem[] = paymentEntitiesData
        ?.abacusReferencePaymentEntities?.items
        ? map(
              paymentEntitiesData.abacusReferencePaymentEntities.items,
              ({ referencePaymentEntityId, paymentEntityName }: any) => ({
                  value: referencePaymentEntityId.toString(),
                  label: paymentEntityName,
              })
          )
        : [];

    return (
        <>
            <MultiSelect
                className={`SelectPaymentEntity ${className}`}
                disabled={isDisabled || paymentEntitiesLoading}
                id="paymentEntity"
                menuMaxWidth={menuMaxWidth}
                menuMinWidth={menuMinWidth}
                onChange={onChange}
                options={paymentEntitiesOptions}
                placeholder={SEARCH_PLACEHOLDER}
                requireApply={requireApply}
                selectedValue={value}
                testId="SelectPaymentEntity"
                compact={compact}
            />
        </>
    );
};
