import React, { useEffect, useState } from 'react';
import { Dropdown } from '@theorchard/suite-components';
import { useStatementPeriodsList } from 'src/apollo/queries/statement-periods';
import type { DropdownOption } from '@theorchard/suite-components';
import type { GetStatementPeriodsListQuery as AbacusStatementPeriodsList } from 'src/apollo/queries/statement-periods/__generated__/get-statement-periods-list';

export interface StatementPeriodSelectPropTypes {
    className?: string;
    clearable?: boolean;
    disabled?: boolean;
    id: string;
    isMultiSelect?: boolean;
    onChange: any;
    name: string;
    placeholder?: string;
    value: string;
}

interface SearchDropdownOption extends DropdownOption {
    type?: string;
}

export const StatementPeriodSelect: React.FC<
    StatementPeriodSelectPropTypes
> = ({
    className = '',
    clearable = true,
    disabled = false,
    id,
    isMultiSelect = false,
    name,
    onChange,
    placeholder = '',
    value,
}) => {
    const [statementPeriods, setStatementPeriods] = useState([]);

    const { data, loading } = useStatementPeriodsList(1000, 0);
    useEffect(() => {
        if (data) {
            const { abacusStatementPeriodsList }: AbacusStatementPeriodsList =
                data;
            if (abacusStatementPeriodsList) {
                const options: any = abacusStatementPeriodsList.items.map(
                    ({ statementPeriodName, statementPeriodId }) => ({
                        label: statementPeriodName,
                        value: statementPeriodId,
                    })
                );
                setStatementPeriods(options);
            }
        }
    }, [data]);

    const getSelectedOption = <T extends SearchDropdownOption>(
        options: T[],
        selectedValue?: string | T
    ) => {
        let selectedOptionOrDefault: T | undefined;
        if (selectedValue !== undefined)
            if (typeof selectedValue === 'string')
                selectedOptionOrDefault = options.find(
                    option => option.value === selectedValue
                );
            else
                selectedOptionOrDefault =
                    options.find(
                        option => option.value === selectedValue.value
                    ) || selectedValue;
        return selectedOptionOrDefault;
    };

    return (
        <>
            <Dropdown
                controlled
                className={`SelectStatementPeriod ${className}`}
                closeMenuOnSelect={!isMultiSelect}
                id={id}
                isClearable={clearable}
                isDisabled={disabled}
                isMulti={isMultiSelect}
                name={name}
                onChange={onChange}
                options={statementPeriods}
                value={getSelectedOption(statementPeriods, value)}
                placeholder={placeholder}
                isLoading={loading}
            />
        </>
    );
};
