import StyledWrapper from "@insite/client-framework/Common/StyledWrapper";
import { GetWishListsApiParameter } from "@insite/client-framework/Services/WishListService";
import translate from "@insite/client-framework/Translate";
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;
    getAutocompleteModel: Function;
    updateLoadParameter: Function;
}

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

export const searchFieldBrandStyles: MyListsSearchFieldBrandStyles = {
    optionWrapper: {
        css: css`
            display: flex;
            cursor: pointer;
        `,
    },
    infoWrapper: {
        css: css`
            display: flex;
            flex-direction: column;
        `,
    },
    autocompleteTitleText: {
        size: 14,
    },
    autocompleteValueText: {
        size: 14,
        css: css`
            margin-top: 5px;
        `,
    },
};
const styles = searchFieldBrandStyles;

type Props = OwnProps;

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

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

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

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

            setSearch(query);
            getAutocompleteModel({
                query,
                relevancy: false,
                searchOnTyping: true,
                onSuccess: (result: any) => {
                    setIsLoading(false);

                    if (!result?.brands || result.brands.length === 0) {
                        setOptions([]);
                        return;
                    }

                    const uniqueBrands = result.brands.reduce((brands: any, brand: any) => {
                        const existingItem = brands.find((item: { id: any }) => brand.id === item.id);
                        if (!existingItem) {
                            brands.push({ ...brand });
                        }
                        return brands;
                    }, []);

                    const newOptions = uniqueBrands.map((brand: any) => ({
                        optionText: brand.title,
                        optionValue: brand.id || undefined,
                        rowChildren: (
                            <StyledWrapper {...styles.optionWrapper}>
                                <StyledWrapper {...styles.infoWrapper}>
                                    <Typography {...styles.autocompleteTitleText}>{brand.displayTitle}</Typography>
                                </StyledWrapper>
                            </StyledWrapper>
                        ),
                    }));
                    setOptions(newOptions);
                },
                onComplete(resultProps: any) {
                    if (resultProps?.apiResult) {
                        this.onSuccess?.(resultProps?.apiResult);
                    }
                },
            });
        }, 300),
        [],
    );

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

    return (
        <SearchFieldWrapper extendedStyles={styles.wrapper}>
            <DynamicDropdown
                {...styles.searchDynamicDropdown}
                label={translate("Brand")}
                onSelectionChange={onSelectionChangeHandler}
                onInputChange={onInputChanged}
                filterOption={() => true}
                selected={getWishListsParameter.brandId}
                options={options}
                hideNoOptionsIfEmptySearch
                isLoading={isLoading}
                placeholder={translate("Search for a brand")}
                search={search}
                data-test-selector="myLists_searchField_brand"
            />
        </SearchFieldWrapper>
    );
};

export default MyListsSearchFieldBrand;
