import React, { useState } from 'react';
import classnames from 'classnames';

export interface OptionProp {
  name: string;
  value: string;
  isActive?: boolean;
}

export interface Props {
  options: OptionProp[];
  selected: string;
  onChange: (value: string) => void;
}

const PeriodFilter = ({ options, selected, onChange }: Props) => {
  const [ isOpen, setOpen ] = useState(false);
  const toggleOpen = () => {
    setOpen(!isOpen);
  };
  const close = () => {
    setOpen(false);
  };

  const handleSelection = (option) => () => {
    if (option.isActive && onChange) {
      onChange(option.value);
    }
  };

  const listClassName = classnames('c-period-filter__container', { 'c-period-filter__container--open': isOpen });
  const blockerClassName = classnames('c-blocker', { 'c-blocker--active': isOpen });
  const chevronClassName = classnames('c-period-filter__chevron', { 'icon-flat-arrow-up': isOpen, 'icon-flat-arrow-down': !isOpen });

  return <>
    <div className={blockerClassName} onClick={close}/>
    <div className="c-period-filter__input-container u-position--relative" onClick={toggleOpen}>
      <button className="c-period-filter__input">
        <p className="c-period-filter__input-text ">
          <i className="icon-calendar u-margin-right"/>{options.find(option => option.value === selected)?.name ?? 'Select period'}
        </p>
      </button>
      <i className={chevronClassName}/>
    </div>
    <div className={listClassName}>
      <div className="c-period-filter__pop-up">
        <div className="c-period-filter__items">
          {options.map(option => {
            const itemClassName = classnames('c-period-filter__item', { 'c-period-filter__item--disabled': !option.isActive });
            return <div className={itemClassName} key={option.value} onClick={handleSelection(option)}>
              <i className="icon-calendar u-margin-right"/>{option.name}
              {option.value === selected && <i className="icon-checkmark c-period-filter__selected"/>}
            </div>;
          })}
        </div>
        <div className="c-period-filter__scroller"/>
      </div>
    </div>
  </>;
};

export default PeriodFilter;
