import React, {
    useEffect,
    useMemo,
    type Dispatch,
    type SetStateAction,
} from 'react';
import { Select } from '@theorchard/suite-components';
import { useReferenceSigningEntities } from 'src/apollo/queries/reference-signing-entity';
import type { ListViewItem } from '@theorchard/suite-components';

export interface ReferenceSigningEntityDropdownPropTypes {
    className?: string;
    isClearable?: boolean;
    isDisabled?: boolean;
    id: string;
    onChange: (e: ListViewItem | undefined) => void;
    paymentEntityId: string | null;
    placeholder?: string;
    setSapProfitCenters: Dispatch<SetStateAction<Record<string, any>>>;
    testId?: string;
    value: string | null;
}

export const ReferenceSigningEntityDropdown: React.FC<
    ReferenceSigningEntityDropdownPropTypes
> = ({
    className = '',
    isClearable = true,
    isDisabled = false,
    id,
    onChange,
    paymentEntityId = null,
    placeholder = '',
    setSapProfitCenters,
    testId = 'ReferenceSigningEntityDropdown',
    value,
}) => {
    const { data: signingEntities } = useReferenceSigningEntities();

    const { options, profitCenters } = useMemo(() => {
        const items =
            signingEntities?.abacusReferenceSigningEntities?.items || [];
        const signingEntitiesOptions: ListViewItem[] = [];
        const sapProfitCenters: Record<string, any> = {};

        items.forEach(
            ({
                referencePaymentEntity,
                referenceSigningEntityId,
                legalName,
                authorizedProfitCenters,
            }) => {
                const matchesPaymentEntity =
                    !paymentEntityId ||
                    referencePaymentEntity?.referencePaymentEntityId ===
                        paymentEntityId;

                if (matchesPaymentEntity) {
                    signingEntitiesOptions.push({
                        value: referenceSigningEntityId,
                        label: legalName,
                    });
                    sapProfitCenters[referenceSigningEntityId] =
                        authorizedProfitCenters;
                }
            }
        );

        return {
            options: signingEntitiesOptions,
            profitCenters: sapProfitCenters,
        };
    }, [signingEntities, paymentEntityId]);

    useEffect(() => {
        setSapProfitCenters(profitCenters);
    }, [profitCenters, setSapProfitCenters]);

    return (
        <>
            <Select
                className={`SelectSigningEntity ${className}`}
                disabled={isDisabled}
                id={id}
                hideClearButton={!isClearable}
                onChange={onChange}
                options={options}
                placeholder={placeholder}
                selectedValue={value || undefined}
                testId={testId}
            />
        </>
    );
};

export default ReferenceSigningEntityDropdown;
