import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import getBoldedText from "@insite/client-framework/Common/Utilities/getPatternBolded";
import { GetWishListsApiParameter } from "@insite/client-framework/Services/WishListService";
import translate from "@insite/client-framework/Translate";
import { WishListModel } from "@insite/client-framework/Types/ApiModels";
import SearchFieldWrapper, {
    SearchFieldWrapperStyles,
} from "@insite/content-library/Widgets/OrderHistory/SearchFieldWrapper";
import DynamicDropdown, { DynamicDropdownPresentationProps, OptionObject } from "@insite/mobius/DynamicDropdown";
import Typography, { TypographyPresentationProps } from "@insite/mobius/Typography";
import InjectableCss from "@insite/mobius/utilities/InjectableCss";
import debounce from "lodash/debounce";
import React, { ChangeEvent, useCallback, useEffect, useState } from "react";
import { css } from "styled-components";

interface OwnProps {
    getWishListsParameter: GetWishListsApiParameter;
    updateLoadParameter: Function;
    loadWishListsData: Function;
}

export interface MyListsSearchFieldSharedByStyles {
    wrapper?: SearchFieldWrapperStyles;
    searchDynamicDropdown?: DynamicDropdownPresentationProps;
    optionWrapper?: InjectableCss;
    infoWrapper?: InjectableCss;
    autocompleteTitleText?: TypographyPresentationProps;
}

export const searchFieldSharedByStyles: MyListsSearchFieldSharedByStyles = {
    optionWrapper: {
        css: css`
            display: flex;
            cursor: pointer;
        `,
    },
    infoWrapper: {
        css: css`
            display: flex;
            flex-direction: column;
        `,
    },
    autocompleteTitleText: {
        size: 14,
    },
};
const styles = searchFieldSharedByStyles;

type Props = OwnProps;

const MyListsSearchFieldSharedBy = ({ getWishListsParameter, updateLoadParameter, loadWishListsData }: Props) => {
    const [search, setSearch] = useState("");
    const [options, setOptions] = useState<OptionObject[]>([]);
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        setSearch("");
        setOptions([]);
    }, [getWishListsParameter]);

    const onSelectionChangeHandler = (sharedBy?: string) => {
        updateLoadParameter({ sharedBy });
    };

    const debouncedSearchSharedBy = useCallback(
        debounce((query: string) => {
            if (!query) {
                setIsLoading(false);
                setOptions([]);
                return;
            }

            setSearch(query);
            loadWishListsData({
                ...getWishListsParameter,
                pageSize: 10,
                page: undefined,
                sharedBy: undefined,
                sharedByQuery: query,
                expand: undefined,
                sort: undefined,
                wishListLinesSort: undefined,
                onComplete: (result: any) => {
                    setIsLoading(false);

                    const wishListCollection = result?.apiResult?.wishListCollection as WishListModel[];
                    const wishLists = wishListCollection.filter(w => !w.isAutogenerated);
                    if (!wishLists) {
                        setOptions([]);
                        return;
                    }

                    const newOptions = wishLists.map((wishList: WishListModel) => ({
                        optionText: wishList.sharedByUserName,
                        optionValue: wishList.sharedByUserName,
                        rowChildren: (
                            <StyledWrapper {...styles.optionWrapper}>
                                <StyledWrapper {...styles.infoWrapper}>
                                    <Typography {...styles.autocompleteTitleText}>
                                        {getBoldedText(wishList.sharedByUserName, query)}
                                    </Typography>
                                </StyledWrapper>
                            </StyledWrapper>
                        ),
                    }));
                    setOptions(newOptions);
                },
            } as GetWishListsApiParameter);
        }, 300),
        [],
    );

    const onInputChanged = (event: ChangeEvent<HTMLInputElement>) => {
        setIsLoading(true);
        debouncedSearchSharedBy(event.target.value);
    };

    return (
        <SearchFieldWrapper extendedStyles={styles.wrapper}>
            <DynamicDropdown
                {...styles.searchDynamicDropdown}
                label={translate("Shared By")}
                onSelectionChange={onSelectionChangeHandler}
                onInputChange={onInputChanged}
                filterOption={() => true}
                selected={getWishListsParameter.sharedBy}
                options={options}
                hideNoOptionsIfEmptySearch
                isLoading={isLoading}
                placeholder={translate("Search by username")}
                search={search}
                data-test-selector="myLists_searchField_sharedBy"
            />
        </SearchFieldWrapper>
    );
};

export default MyListsSearchFieldSharedBy;
