import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { ALPHABETICAL, RANDOM } from '../../constants/sorting';
import { productSimilarAppsSchemaForm } from '../../constants/components/schemas/product-similar-apps';
import { productSimilarAppsDataShape, productSimilarAppsSettingsShape } from '../../constants/components/prop-types/product-similar-apps';
import Slider from '../../atoms/slider/Slider';
import withListener from '../withListener';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductSimilarApps.scss';

const n = createNamespace('ProductSimilarApps');

export const sortList = (sortBy, list) => {
    if (sortBy && list && list.length) {
        const sortedList = [...list];

        switch (sortBy) {
            case ALPHABETICAL.value:
                return sortedList.sort((a, b) => {
                    if (a.name < b.name) { return -1; }
                    if (a.name > b.name) { return 1; }
                    return 0;
                });
            case RANDOM.value:
                sortedList.forEach((item, index) => {
                    const randomIndex = Math.floor(Math.random() * (index + 1));
                    [sortedList[index], sortedList[randomIndex]] = [sortedList[randomIndex], sortedList[index]];
                });

                return sortedList;
            default:
                return sortedList;
        }
    }

    return list;
};

export const ProductSimilarAppsComponent = ({
    data: {
        recommendations = {},
        i18n: i18nProductList
    },
    settings
}) => {
    const {
        items,
        viewAllLink,
        i18n: i18nRecommendations
    } = recommendations;

    const [sortedItems, setSortedItems] = useState(items);

    const componentSettings = {
        ...ProductSimilarAppsComponent.defaultProps.settings,
        ...settings
    };
    const { sortBy, sliderOptions: isSlider, maxRows, buttonLabel } = componentSettings;

    useEffect(() => {
        const newSortedItems = sortList(sortBy, items);
        setSortedItems(newSortedItems);
    }, [sortBy, items]);

    if (!sortedItems || !sortedItems.length) {
        return null;
    }
    return (
        <section {...n('container').props}>
            <Slider
                items={sortedItems}
                url={viewAllLink}
                buttonLabel={buttonLabel}
                isSlider={isSlider}
                maxRows={maxRows && Number(maxRows)}
                i18n={i18nProductList}
                staticTitle={i18nRecommendations.titleProduct}
                settings={settings}
            />
        </section>
    );
};

ProductSimilarAppsComponent.schema = () => ({
    name: 'ProductSimilarApps',
    title: 'uieditor.sfbComponent.productSimilarApps.title',
    form: productSimilarAppsSchemaForm,
    marketplaceData: {
        i18n: 'i18n',
        recommendations: 'application.recommendations'
    },
    requiredDataFunc: data => (!!data?.recommendations?.items?.length)
});

ProductSimilarAppsComponent.propTypes = {
    data: PropTypes.shape(productSimilarAppsDataShape),
    settings: PropTypes.shape(productSimilarAppsSettingsShape)
};

ProductSimilarAppsComponent.defaultProps = {
    data: {},
    settings: {}
};

export default withListener(ProductSimilarAppsComponent);
