import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Select from '../select/Select';

const n = createNamespace('mobileNav');

const MobileNav = ({ items, changeQuestionList, currentIndex }) => {
    const [selectedOption, setSelectedOption] = useState(() => {
        if (!items || !items.length) {
            return null;
        }

        return currentIndex !== null && currentIndex !== undefined ? items[currentIndex] : items[0];
    });

    const onChange = ({ value }) => {
        const index = items.findIndex(item => item.value === value);

        if (changeQuestionList) {
            changeQuestionList(index);
        }

        setSelectedOption(items[index]);
    };

    return (
        <div {...n('container').withTestId().props}>
            <Select
                type="button"
                options={items}
                value={selectedOption && selectedOption.value}
                onChange={onChange}
            />
        </div>
    );
};

MobileNav.propTypes = {
    changeQuestionList: PropTypes.func,
    currentIndex: PropTypes.number,
    items: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string,
        value: PropTypes.string
    }))
};

MobileNav.defaultProps = {
    changeQuestionList: null,
    currentIndex: null,
    items: null
};

export default MobileNav;
