import React, { useEffect, useState } from 'react';
import { Select } from '@theorchard/suite-components';
import SelectTruncatedText from 'src/components/shared/select-truncated-text';
import type { ListViewItem } from '@theorchard/suite-components';
import type { AbacusStatementPeriodAdjustmentFileSearchFilterInput } from 'src/apollo/definitions/globalTypes';
import type { GetStatementPeriodAdjustmentFilesSearchQuery } from 'src/apollo/queries/adjustment/__generated__/get-statement-period-adjustment-files-search';

type _AbacusStatementPeriodAdjustmentFilesList = NonNullable<
    GetStatementPeriodAdjustmentFilesSearchQuery['abacusStatementPeriodAdjustmentFilesList']
>;
type AbacusStatementPeriodAdjustmentFile =
    _AbacusStatementPeriodAdjustmentFilesList['items'][0];

const SEARCH_PLACEHOLDER = 'File Name';

export interface AdjustmentsFileNameSearchSelectPropTypes {
    getPromisedAdjustmentFilesSearch: (
        searchFilters: AbacusStatementPeriodAdjustmentFileSearchFilterInput,
        limit?: number,
        offset?: number
    ) => Promise<AbacusStatementPeriodAdjustmentFile[] | undefined>;
    isDisabled?: boolean;
    fieldTextMaxWidth?: number;
    menuMaxWidth?: number;
    onChange: (e: ListViewItem | undefined) => void;
    truncatedTextMaxWidth: number;
    value?: string;
}

export const AdjustmentsFileNameSearchSelect: React.FC<
    AdjustmentsFileNameSearchSelectPropTypes
> = ({
    getPromisedAdjustmentFilesSearch,
    isDisabled = false,
    fieldTextMaxWidth,
    menuMaxWidth,
    onChange,
    truncatedTextMaxWidth,
    value,
}) => {
    const [options, setOptions] = useState<[ListViewItem] | undefined>(
        undefined
    );
    const performSearch = async (term?: string) => {
        if (!term) return {};
        const trimmedTerm = term.trim().replace('\\', '');

        if (trimmedTerm) {
            const data = await getPromisedAdjustmentFilesSearch(
                { fileName: trimmedTerm },
                50,
                0
            );
            const searchResults =
                data?.map((row: AbacusStatementPeriodAdjustmentFile) => ({
                    label: row.fileName,
                    value: row.fileName,
                })) || [];
            return { data: searchResults };
        }
        return {};
    };

    useEffect(() => {
        if (value) setOptions([{ label: value, value }]);
        else setOptions(undefined);
    }, [value]);

    return (
        <Select
            className="AdjustmentFileName-select"
            disabled={isDisabled}
            fieldTextMaxWidth={fieldTextMaxWidth}
            id="fileNameSearch"
            menuMaxWidth={menuMaxWidth}
            onChange={onChange}
            options={options}
            onLoadOptions={performSearch}
            placeholder={SEARCH_PLACEHOLDER}
            selectedValue={value}
            components={{
                OptionLabel: ({ option }) => (
                    <SelectTruncatedText
                        text={option.label || ''}
                        placement="right"
                        maxWidth={truncatedTextMaxWidth}
                    />
                ),
            }}
            compact
        />
    );
};

export default AdjustmentsFileNameSearchSelect;
