import React from 'react'
import PropTypes from 'prop-types'

const List = ({list, tag: Tag}) => {
    if (list.length <= 1) {
        return list[0] || ''
    }
    if (list.length === 2) {
        return (
            <React.Fragment>
                <Tag>{list[0]}</Tag>
                {' and '}
                <Tag>{list[1]}</Tag>
            </React.Fragment>
        )
    }
    const [last, ...first] = list.reverse()
    return (
        <React.Fragment>
            {first.reverse().map((item, i) => (
                <React.Fragment key={i}>
                    <Tag>{item}</Tag>
                    {', '}
                </React.Fragment>
            ))}
            {' and '}
            <Tag>{last}</Tag>
        </React.Fragment>
    )
}

List.defaultProps = {
    tag: 'span',
}

List.propTypes = {
    list: PropTypes.arrayOf(PropTypes.string),
    tag: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
}

export default List
