import React from 'react';
import PropTypes from 'prop-types';
import Slick from 'react-slick';
import './styles/FeaturedCustomers.scss';
import withListener from '../withListener';
import Image from '../../atoms/image/Image';
import { createNamespace } from '../../tools/namingTools';
import { parseToBool, leastCommonMultiple } from '../../tools/helpers';
import { TOGGLE, DROPDOWN } from '../../constants/schemaComponentTypes';
import { NAMESPACES } from '../../constants/namespaces';
import { THREE, FOUR, FIVE } from '../../constants/logoRotateOptions';

const n = createNamespace('FeaturedCustomers');

const sliderSettings = {
    slidesToShow: 4,
    slidesToScroll: 4
};

export const FeaturedCustomersComponent = ({ data, settings }) => {
    const { overview = {} } = data;
    const { customers = [], i18n = {} } = overview;

    if (!customers.length) {
        return null;
    }

    const title = i18n.customers;
    const limit = 10;
    const nSlides = customers.length;
    const isSliderEnabled = settings.autoplay && nSlides > sliderSettings.slidesToShow;
    const componentVariables = {
        nbColumn: sliderSettings.slidesToShow
    };

    let slides;
    const [isGrayscale] = parseToBool(settings.grayscale);

    const renderSlides = slidesData => slidesData.map(({ name, imgSrc }) => {
        const imageModifiers = [isGrayscale ? 'grayscale' : ''];
        const slideModifiers = [isSliderEnabled ? '' : 'static'];

        return (
            <div {...n('slide', slideModifiers).withTestId().withE2EId().props} key={`image-${name}`}>
                <div {...n('imageWrapper').withTestId().props}>
                    <Image {...n('image', imageModifiers).withTestId().withE2EId().props} alt={name} src={imgSrc} />
                </div>
            </div>
        );
    });

    // Resize array if more items than limit
    if (customers.length > limit) {
        customers.length = limit;
    }

    if (isSliderEnabled) {
        // in order to make slider always move by the same number of slides,
        // the total number of slides must be a multiple of the number
        // of visible slides in the viewport
        const padSlidesAmount = leastCommonMultiple(nSlides, sliderSettings.slidesToScroll) - nSlides;
        const padSlides = [];

        for (let duplicateIndex = 0; duplicateIndex < padSlidesAmount; duplicateIndex += 1) {
            padSlides.push(
                {
                    ...customers[duplicateIndex % nSlides],
                    duplicateIndex
                }
            );
        }
        const slidesToRender = [
            ...customers,
            ...padSlides
        ];

        slides = (
            <Slick
                dots={false}
                infinite
                arrows={false}
                autoplay
                autoplaySpeed={settings.autoplaySpeed * 1000}
                speed={2000}
                pauseOnHover
                {...sliderSettings}
            >
                {renderSlides(slidesToRender)}
            </Slick>
        );
    } else {
        slides = renderSlides(customers);
    }

    return (
        <section {...n('wrapper').withTestId().withE2EId().withVariables(componentVariables).props}>
            {title && <h1 {...n('title').withTestId().withE2EId().props}>{title}</h1>}
            <div {...n('container', isSliderEnabled ? '' : 'static').withTestId().withE2EId().props}>
                {slides}
            </div>
        </section>
    );
};

const LOGO_ROTATE_OPTIONS = [THREE, FOUR, FIVE];

FeaturedCustomersComponent.schema = () => ({
    name: 'FeaturedCustomers',
    title: 'uieditor.sfbComponent.featuredCustomers.title',
    iconName: 'users',
    orderableSection: [NAMESPACES.profile],
    form: {
        grayscale: {
            labelOn: 'uieditor.sfbComponent.featuredCustomers.greyscale.labelOn',
            labelOff: 'uieditor.sfbComponent.featuredCustomers.greyscale.labelOff',
            defaultValue: true,
            type: TOGGLE
        },
        autoplay: {
            labelOn: 'uieditor.sfbComponent.featuredCustomers.autoplay.labelOn',
            labelOff: 'uieditor.sfbComponent.featuredCustomers.autoplay.labelOff',
            defaultValue: true,
            type: TOGGLE
        },
        autoplaySpeed: {
            title: 'uieditor.sfbComponent.featuredCustomers.autoplaySpeed.title',
            defaultValue: LOGO_ROTATE_OPTIONS[0].value,
            type: DROPDOWN,
            options: LOGO_ROTATE_OPTIONS,
            conditionalAttributes: {
                isDisabled: {
                    when: 'autoplay',
                    connector: 'equals',
                    value: false
                }
            }
        }
    },
    marketplaceData: {
        overview: 'application.overview'
    },
    requiredDataFunc: ({ overview: { customers = [] } }) => (customers && customers.length)
});

FeaturedCustomersComponent.propTypes = {
    settings: PropTypes.shape({
        grayscale: PropTypes.bool,
        autoplay: PropTypes.bool,
        autoplaySpeed: PropTypes.number
    }),
    data: PropTypes.shape({
        overview: PropTypes.shape({
            customers: PropTypes.arrayOf(PropTypes.shape({
                name: PropTypes.string,
                imgSrc: PropTypes.string
            })),
            i18n: PropTypes.shape({
                customers: PropTypes.string
            })
        })
    })
};

const SETTINGS = FeaturedCustomersComponent.schema().form;

FeaturedCustomersComponent.defaultProps = {
    settings: {
        grayscale: SETTINGS.grayscale.defaultValue,
        autoplay: SETTINGS.autoplay.defaultValue,
        autoplaySpeed: SETTINGS.autoplaySpeed.defaultValue
    },
    data: {
        overview: {
            customers: [{
                name: '',
                imgSrc: ''
            }],
            i18n: {
                title: 'Featured Customers'
            }
        }
    }
};

export default withListener(FeaturedCustomersComponent);
