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

const n = createNamespace('mobileNav');

const MobileNav = ({
    items,
    changeQuestionList,
    currentIndex,
    label,
    className: extraClass
}) => {
    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().withClass(extraClass).props}>
            <Select
                type="button"
                name="faq-category-select"
                options={items}
                label={label}
                value={selectedOption && selectedOption.value}
                onChange={onChange}
            />
        </div>
    );
};

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

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

export default MobileNav;
