import React, { useState } from 'react';
import PropTypes from 'prop-types';
import './styles/DotsNav.scss';
import { createNamespace } from '../../tools/namingTools';

const n = createNamespace('DotsNav');

const DotsNav = ({
    nItems,
    currentIndex,
    nDotsVisible,
    goTo
}) => {
    const [currentTranslate, setCurrentTranslate] = useState(0);
    const isOutBeforeViewport = currentIndex < currentTranslate;
    const isOutAfterViewport = currentIndex > currentTranslate + nDotsVisible - 2;
    // dot won't be visible in viewport, we need to move dots so it becomes visible
    let moveAmount = 0;
    if (isOutBeforeViewport) {
        moveAmount = currentIndex - currentTranslate;
    } else if (isOutAfterViewport) {
        moveAmount = currentIndex - (currentTranslate + nDotsVisible - 1);
    }
    if (moveAmount) {
        const nextTranslate = Math.min(Math.max(0, currentTranslate + moveAmount), nItems - nDotsVisible);
        setCurrentTranslate(nextTranslate);
    }

    const dots = [];
    for (let i = 0; i < nItems; i += 1) {
        const distanceFromStartEdge = i - currentTranslate;
        const distanceFromEndEdge = i - (currentTranslate + nDotsVisible - 1);
        const modifiers = [];
        if (i === currentIndex) {
            modifiers.push('active');
        }

        // show dots at or left of start edge smaller, unless it is the first dot at the edge
        if (distanceFromStartEdge < 0) {
            modifiers.push(`minus-${distanceFromStartEdge * -1}`);
        }
        // show dots at or right of end smaller, unless it is the last dot at the edge
        if (distanceFromEndEdge > 0) {
            modifiers.push(`minus-${distanceFromEndEdge}`);
        }

        const onClick = goTo ? () => goTo(i) : null;

        dots.push(
            (
                <button
                    {...n('dot', modifiers).withTestId().props}
                    onClick={onClick}
                    key={i}
                    type="button"
                >
                    {i}
                </button>
            )
        );
    }
    // const translateDots = currentTranslate * dotWidth * -1;
    const cssVariables = {
        'dots-translate': currentTranslate,
        'max-dots': nDotsVisible > nItems ? nItems : nDotsVisible
    };
    return (
        <div {...n('wrapper').withVariables(cssVariables).props}>
            <div {...n('viewport').props}>
                {dots}
            </div>
        </div>
    );
};

DotsNav.propTypes = {
    nItems: PropTypes.number,
    currentIndex: PropTypes.number,
    nDotsVisible: PropTypes.number,
    goTo: PropTypes.func
};

DotsNav.defaultProps = {
    nItems: 0,
    currentIndex: 0,
    nDotsVisible: 5,
    goTo: null
};

export default DotsNav;
