import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames/bind';
import moment from 'moment';
import { ChevronsLeft, ChevronsRight } from 'react-feather';
import styles from './datepicker.scss';
import Button from '../Button';
import OutsideWrapper from '../Utilities/OutsideWrapper';

const cx = classnames.bind(styles);

const View = ({ currentValue, availableValues, format, onClick }) => {
  const [open, setOpen] = useState(false);

  return (
    <OutsideWrapper onOutside={() => setOpen(false)}>
      <span className={cx('datepicker__calendar_header__view')}>
        <Button
          onClick={() => {
            setOpen(!open);
          }}
          theme="secondary"
          small
        >
          {moment(currentValue).format(format)}
        </Button>

        {open && (
          <div className={cx('datepicker__calendar_header__view_container')}>
            {availableValues.map((value, index) => {
              const isCurrent = moment(currentValue).format(format) === value;

              return (
                <span
                  key={value}
                  className={cx(
                    'datepicker__calendar_header__view_container__item',
                    {
                      datepicker__calendar_header__view_container__item__selected: isCurrent,
                    }
                  )}
                >
                  <Button theme="clear" small onClick={() => onClick(value)}>
                    {index === 0 && <ChevronsLeft size={22} />}
                    {value}
                    {index === availableValues.length - 1 && (
                      <ChevronsRight size={22} />
                    )}
                  </Button>
                </span>
              );
            })}
          </div>
        )}
      </span>
    </OutsideWrapper>
  );
};

View.defaultProps = {
  currentValue: undefined,
};

View.propTypes = {
  currentValue: PropTypes.instanceOf(Date),
  availableValues: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.string),
    PropTypes.arrayOf(PropTypes.number),
  ]).isRequired,
  format: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired,
};

export default View;
