import React, { useEffect, useState } from 'react';
import { MultiSelect, TruncatedText } from '@theorchard/suite-components';
import { useParams } from 'react-router-dom';
import { useWorksheetAdjustmentsAccountsSearch } from 'src/apollo/queries/adjustment';
import type { GetAbacusWorksheetAdjustmentsAccountsQuery } from 'src/apollo/queries/adjustment/__generated__/get-abacus-worksheet-adjustments-accounts';
import type { ListViewItem } from '@theorchard/suite-components';

type AbacusWorksheetAdjustmentAccount = Extract<
    NonNullable<
        GetAbacusWorksheetAdjustmentsAccountsQuery['abacusWorksheetAdjustmentsAccounts']
    >['items'][0],
    { __typename?: 'AbacusWorksheetAdjustmentAccount' }
> | null;

const FILTER_PLACEHOLDER = 'Search by Account Name or ID';

const SEARCH_PLACEHOLDER = 'Account';

export interface AdjustmentsAccountsSelectPropTypes {
    className?: string;
    compact?: boolean;
    isFilterCleared: boolean;
    isDisabled?: boolean;
    menuMaxWidth?: number;
    onChange: (e: ListViewItem[] | undefined) => void;
    optionTagMaxWidth?: number;
    truncatedTextMaxWidth: number;
}

export const AdjustmentsAccountsSelect: React.FC<
    AdjustmentsAccountsSelectPropTypes
> = ({
    className = '',
    compact = false,
    isFilterCleared,
    isDisabled = false,
    menuMaxWidth,
    onChange,
    optionTagMaxWidth,
    truncatedTextMaxWidth,
}) => {
    const { batchId } = useParams<{
        batchId: string;
    }>();

    const [isSelectedValueCleared, setIsSelectedValueCleared] =
        useState<boolean>(false);

    const getPromisedAdjustmentsAccountsSearch =
        useWorksheetAdjustmentsAccountsSearch();

    const onLoadOptionsHandler = async (term?: string) => {
        setIsSelectedValueCleared(false);
        if (!term) return {};
        const trimmedTerm = term.trim().replace('\\', '');

        if (trimmedTerm) {
            const data = await getPromisedAdjustmentsAccountsSearch(
                batchId,
                { accountSearchTerm: trimmedTerm },
                20,
                0
            );
            const searchResults =
                data?.map(
                    (adjustmentAccount: AbacusWorksheetAdjustmentAccount) => ({
                        label: `${adjustmentAccount!.account.accountName} - ${adjustmentAccount!.account.accountId}`,
                        value: adjustmentAccount!.account.accountId,
                    })
                ) || [];
            return { data: searchResults };
        }

        return {};
    };

    useEffect(() => {
        if (isFilterCleared) setIsSelectedValueCleared(isFilterCleared);
    }, [isFilterCleared]);

    return (
        <MultiSelect
            className={`SelectAdjustmentAccount ${className}`}
            disabled={isDisabled}
            id="adjustmentAccount"
            filterPlaceholder={FILTER_PLACEHOLDER}
            menuMaxWidth={menuMaxWidth}
            onChange={onChange}
            onLoadOptions={onLoadOptionsHandler}
            optionTagMaxWidth={optionTagMaxWidth}
            placeholder={SEARCH_PLACEHOLDER}
            requireApply
            components={{
                OptionLabel: ({ option }) => (
                    <TruncatedText
                        text={option.label || ''}
                        maxWidth={truncatedTextMaxWidth}
                    />
                ),
            }}
            compact={compact}
            selectedValue={isSelectedValueCleared ? [] : undefined}
        />
    );
};

export default AdjustmentsAccountsSelect;
