import * as React from 'react';

import WrapperAccordion from './AccordionWrapper';

interface IProps {
  items: {
    header: string| React.ReactNode |React.ReactChild;
    content: string| React.ReactNode |React.ReactChild;
    labels?: string| React.ReactNode |React.ReactChild;
  }[];
  automatic?: boolean;
}

interface IState {
  active: null | boolean | number;
  activeIndex: number | null;
}

export default class Accordion extends React.PureComponent<IProps, IState> {
  state = {
    active: false,
    activeIndex: null,
  }

  toggle = (e: boolean, index: number) => {
    this.setState(({ active: e, activeIndex: index }));
    if (e && this.props.automatic && this.state.activeIndex === index) {
      this.setState({ activeIndex: null });
    }
  }

  render = () => {
    return this.props.items.map((item, index) => (
      <WrapperAccordion
        active={index}
        activeIndex={this.state.activeIndex}
        key={index}
        click={(e) => this.toggle(e, index)}
        header={item.header}
        content={item.content}
        labels={item.labels}
        automatic={this.props.automatic}
      />
    ));
  }
}