import React, { useRef, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import DOMPurify from 'dompurify';
import { lighten, darken } from '../../tools/colorHelper';
import { createNamespace } from '../../tools/namingTools';
import { BUTTON_THEMES as buttonThemes, THEME_PRIMARY } from '../../constants/buttons';
import FormLabel from '../form-label/FormLabel';
import ButtonIcon from '../button-icon/ButtonIcon';
import Icon, { allowedTypes as iconTypes } from '../icon/Icon';
import useClickOutside from '../../tools/hooks/useClickOutside';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/InputSearch.scss';

const n = createNamespace('InputSearch');

const InputSearch = ({
    name,
    label,
    required,
    placeholder,
    defaultValue,
    hiddenLabel,
    inputRef,
    inputClass,
    submitLabel,
    submitIcon,
    submitIconUrl,
    submitIconAlt,
    submitIconColor,
    submitIconOnly,
    submitTextOnly,
    submitColorTheme,
    submitBgColor,
    withBorder,
    borderRadius,
    searchPlaceholderTextColor,
    backgroundColor,
    borderColor,
    height,
    boxShadow,
    onChange,
    suggestionsData,
    locale
}) => {
    const searchRef = useRef();
    const inputTextRef = useRef();
    const [suggestionsWidth, setSuggestionsWidth] = useState();
    const { data, error } = suggestionsData;
    const hits = data?.publishedProductsSearchSuggest?.hits;
    const [activeItemId, setActiveItemId] = useState(-1);
    const hasSuggestions = hits?.length > 0;
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [searchText, setSearchText] = useState(defaultValue);
    const [usedKeyboard, setUsedKeyboard] = useState(false);
    const [pressedTab, setPressedTab] = useState(false);

    const componentVariables = {
        'input-bg-color': backgroundColor,
        'input-border-width': withBorder ? '1px' : '0',
        'input-border-radius': borderRadius && `${borderRadius}px`,
        'input-border-color': borderColor,
        'input-border-focus-color': borderColor && darken(borderColor, 0.25),
        'input-height': height && `${height}px`,
        'submit-bg-color': submitBgColor,
        'submit-bg-hover-color': submitBgColor && lighten(submitBgColor, 0.08),
        'submit-icon-color': submitIconColor,
        'search-placeholder-text-color': searchPlaceholderTextColor
    };

    const controlModifiers = [
        submitLabel && 'with-button',
        !boxShadow && 'no-box-shadow',
        searchPlaceholderTextColor && 'with-placeholder-color'
    ];

    const labelModifiers = [
        hiddenLabel && 'hidden'
    ];

    const submitModifiers = [
        submitBgColor && 'custom-bg-color',
        borderColor && 'input-border-color'
    ];

    const clickAwayHandler = e => {
        setShowSuggestions(false);
        onChange(e);
    };

    useClickOutside(searchRef, clickAwayHandler);

    const handleKeyDown = event => {
        if (!hits?.length) { return; }
        switch (event.key) {
            case 'ArrowUp':
            case 'ArrowLeft': {
                event.preventDefault();
                setUsedKeyboard(true);
                if (activeItemId === -1) {
                    setActiveItemId(hits.length - 1);
                    const inputElement = inputTextRef.current;
                    inputElement.value = hits[hits.length - 1].productName;
                } else {
                    const prevIndex = (activeItemId - 1 + hits.length) % hits.length;
                    setActiveItemId(prevIndex);
                    const inputElement = inputTextRef.current;
                    inputElement.value = hits[prevIndex].productName;
                }
                break;
            }
            case 'ArrowDown':
            case 'ArrowRight': {
                event.preventDefault();
                setUsedKeyboard(true);
                const nextIndex = (activeItemId + 1) % hits.length;
                if (activeItemId === hits.length - 1) {
                    setActiveItemId(-1);
                    const inputElement = inputTextRef.current;
                    inputElement.value = searchText;
                } else {
                    setActiveItemId(nextIndex);
                    const inputElement = inputTextRef.current;
                    inputElement.value = hits[nextIndex].productName;
                }
                break;
            }
            case 'Escape': {
                event.preventDefault();
                setShowSuggestions(false);
                break;
            }
            case 'Enter': {
                if (activeItemId !== -1 && usedKeyboard) {
                    event.preventDefault();
                    const { productId } = hits[activeItemId];
                    window.location.href = `/${locale}/apps/${productId}`;
                }
                break;
            }
            case 'Tab': {
                setPressedTab(true);
                setShowSuggestions(false);
                onChange(event);
                break;
            }
            default:
                break;
        }
    };

    const handleOnChange = e => {
        setActiveItemId(-1);
        setSearchText(e.target.value);
        onChange(e);
    };

    const handleOnFocus = e => {
        hasSuggestions && setShowSuggestions(true);
        const inputElement = inputTextRef.current;
        if (inputElement) {
            const len = inputElement.value.length;
            inputElement.setSelectionRange(len, len);
        }
        setPressedTab(false);
        onChange(e);
    };

    const handleRef = ref => {
        inputRef && inputRef(ref);
        inputTextRef.current = ref;
    };

    const handleClick = () => {
        hasSuggestions && setShowSuggestions(true);
    };

    const handleOnMouseOver = (event, index) => {
        const id = Number(index);
        setActiveItemId(id);
        setUsedKeyboard(false);
    };

    useEffect(() => {
        if (searchRef?.current) {
            const { width } = searchRef.current.getBoundingClientRect();
            setSuggestionsWidth(width);
        }
        if (!pressedTab) {
            setShowSuggestions(hasSuggestions);
        }
    }, [data, hasSuggestions]);

    const renderSubmitbutton = (
        <ButtonIcon
            {...n('submitBtn', submitModifiers).props}
            size="input"
            theme={submitBgColor ? null : submitColorTheme}
            action="submit"
            icon={!submitTextOnly && !submitIconUrl ? submitIcon : null}
            iconSrc={submitIconUrl}
            iconAlt={submitIconAlt}
            iconClass={n('submitIcon').props.className}
            hiddenText={submitIconOnly}
        >
            {submitLabel}
        </ButtonIcon>
    );

    const renderInput = (
        <input
            {...n('control', controlModifiers).withTestId().withClass(inputClass).props}
            id={name}
            type="search"
            name={name}
            ref={handleRef}
            placeholder={placeholder}
            defaultValue={defaultValue}
            required={required}
            onChange={handleOnChange}
            onKeyDown={handleKeyDown}
            aria-label={placeholder}
            onFocus={handleOnFocus}
            onClick={handleClick}
            autoComplete="off"
        />
    );

    const suggestions = () => {
        const suggestionsList = data
            && hits?.map((product, index) => {
                const active = index === activeItemId ? 'active' : '';
                const productImageUrl = product.productListingImageUrl;
                const highlightedText = product?.highlights?.[0]?.highlightedTexts?.[0];
                return (
                    <a
                        {...n('suggestionsItem', active).props}
                        key={product.productId}
                        href={`/${locale}/apps/${product.productId}`}
                        onMouseOver={e => handleOnMouseOver(e, index)}
                        onFocus={e => handleOnMouseOver(e, index)}
                    >
                        {productImageUrl
                            ? <img width="16px" src={productImageUrl} alt="" />
                            : <Icon width="16px" type="appIcon" />}
                        <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(highlightedText) }} />
                    </a>
                );
            });

        return !error && hasSuggestions && (
            <div
                {...n('suggestions').withTestId().props}
                style={{
                    width: suggestionsWidth
                }}
            >
                {suggestionsList}
            </div>
        );
    };

    return (
        <div
            {...n('wrapper').withTestId().withVariables(componentVariables).props}
            ref={searchRef}
        >
            <FormLabel
                labelText={label}
                htmlFor={name}
                labelProps={n('label', labelModifiers).props}
            />
            <div {...n('input').withTestId().props}>
                {renderInput}
                {submitLabel && (
                    <div {...n('submitWrapper').withTestId().props}>
                        {renderSubmitbutton}
                    </div>
                )}
            </div>
            {showSuggestions && suggestions()}
        </div>
    );
};

InputSearch.propTypes = {
    name: PropTypes.string,
    label: PropTypes.string,
    required: PropTypes.bool,
    placeholder: PropTypes.string,
    defaultValue: PropTypes.string,
    inputRef: PropTypes.func,
    inputClass: PropTypes.string,
    submitLabel: PropTypes.string,
    submitIcon: PropTypes.oneOf(iconTypes),
    submitIconOnly: PropTypes.bool,
    submitTextOnly: PropTypes.bool,
    submitIconUrl: PropTypes.string,
    submitIconAlt: PropTypes.string,
    submitIconColor: PropTypes.string,
    submitColorTheme: PropTypes.oneOf(buttonThemes),
    submitBgColor: PropTypes.string,
    hiddenLabel: PropTypes.bool,
    withBorder: PropTypes.bool,
    borderRadius: PropTypes.number,
    searchPlaceholderTextColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    borderColor: PropTypes.string,
    height: PropTypes.number,
    boxShadow: PropTypes.bool,
    onChange: PropTypes.func,
    locale: PropTypes.string,
    suggestionsData: PropTypes.shape({
        data: PropTypes.object,
        error: PropTypes.object
    })
};

InputSearch.defaultProps = {
    name: 'inputSearch',
    label: 'Search',
    required: true,
    placeholder: null,
    defaultValue: '',
    inputRef: null,
    inputClass: null,
    submitLabel: null,
    submitIcon: 'search',
    submitIconOnly: false,
    submitTextOnly: false,
    submitIconUrl: null,
    submitIconAlt: null,
    submitIconColor: null,
    submitColorTheme: THEME_PRIMARY,
    submitBgColor: null,
    hiddenLabel: false,
    withBorder: true,
    borderRadius: null,
    searchPlaceholderTextColor: null,
    backgroundColor: null,
    borderColor: null,
    height: null,
    boxShadow: true,
    onChange: () => { },
    locale: 'en-US',
    suggestionsData: {
        data: {},
        error: {}
    }
};

export default InputSearch;
