import * as React from 'react';
import Icons from '../Icons';

import { Content, Header, Wrapper } from './Accordion.styled';

interface IProps {
  header: string| React.ReactNode |React.ReactChild;
  content: string| React.ReactNode |React.ReactChild;
  labels?: string| React.ReactNode |React.ReactChild;
  click: (e?: any) => any;
  active: boolean | number;
  automatic?: boolean;
  activeIndex: null | number;
}

interface IState {
  initialHeight: number;
  active: boolean | number;
}

export default class WrapperAccordion extends React.Component<IProps, IState> {
  accordionRef = React.createRef();
  state = {
    initialHeight: 0,
    active: false,
  }

  componentDidMount() {
    // @ts-ignore
    const initialHeight = this.accordionRef.current.childNodes[0].clientHeight || 0;
    this.setState({ initialHeight });
  }

  onToggle = () => this.setState(prevState => ({
    active: !prevState.active
  }), this.props.click(this.state.active));

  isAutomatic = () => this.props.activeIndex === this.props.active;

  isActive = () => (this.props.automatic) ? this.isAutomatic() : this.state.active;

  render = () => (
    <Wrapper
      active={this.isActive()}
      // @ts-ignore
      ref={this.accordionRef}
      initialHeight={this.state.initialHeight}
    >
      <Header onClick={this.onToggle} active={this.isActive()}>
        {this.props.header}
        <div className='label-icons'>
          {this.props.labels}
          <Icons.Arrow degree={this.isActive() ? 0 : 180} width={20} height={20} />
        </div>
      </Header>
      <Content>{this.props.content}</Content>
    </Wrapper>
  )
}