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

type AbacusWorksheetAdjustmentContract = Extract<
    NonNullable<
        GetAbacusWorksheetAdjustmentsContractsQuery['abacusWorksheetAdjustmentsContracts']
    >['items'][0],
    { __typename?: 'AbacusWorksheetAdjustmentContract' }
> | null;

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

const SEARCH_PLACEHOLDER = 'Contract';

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

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

    const [additionalProps, setAdditionalProps] = useState<
        Partial<MultiSelectProps>
    >({});

    const getPromisedAdjustmentsContractsSearch =
        useWorksheetAdjustmentsContractsSearch();

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

        if (trimmedTerm) {
            const data = await getPromisedAdjustmentsContractsSearch(
                batchId,
                { contractSearchTerm: trimmedTerm },
                20,
                0
            );
            const searchResults =
                data?.map(
                    (
                        adjustmentContract: AbacusWorksheetAdjustmentContract
                    ) => ({
                        label: `${adjustmentContract!.contract.contractName} - ${adjustmentContract!.contract.contractId}`,
                        value: adjustmentContract!.contract.contractId,
                    })
                ) || [];
            return { data: searchResults };
        }

        return {};
    };

    useEffect(() => {
        if (isFilterCleared) {
            setAdditionalProps({ selectedValue: [] });
        }
    }, [isFilterCleared]);

    return (
        <MultiSelect
            className={`SelectAdjustmentContract ${className}`}
            disabled={isDisabled}
            id="adjustmentContract"
            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}
            {...additionalProps}
        />
    );
};

export default AdjustmentsContractsSelect;
