import * as React from 'react';

import { Navigation, Smooth } from './Anchor.styled';

interface Anchors {
  id: string;
  text: string;
}

interface IProps {
  anchors: Anchors[]
}

interface IState {
  active: number|null;
  axisZ: boolean,
}

export default class Anchor extends React.PureComponent<IProps, IState> {
  state = {
    active: null,
    axisZ: false,
  }
  ref = React.createRef<HTMLUListElement>();

  componentDidMount() {
    const elements = this.props.anchors.map((anchor, index) => ({
      id: anchor.id,
      elementPosition: (document.getElementById(anchor.id) as any).offsetTop,
      index,
    }));

    document.addEventListener('scroll', () => {
      const hasActive = elements.filter(element => element.elementPosition <= window.scrollY);
      const lengthHasActive = hasActive.length;
      if (window.scrollY>= elements[0].elementPosition) {
        const lastValue = lengthHasActive >= 0 ? hasActive[lengthHasActive - 1].index : null;
        this.setState({ active: lastValue });
      } else {
        this.setState({ active: null });
      }

      if (document.body.offsetHeight < (scrollY * 2) + 10) {
        this.setState({ active: elements[elements.length - 1].index });
      }

      this.setAxisZ();
    });
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', () => null);
  }

  setAxisZ = () => {
    const { top } = this.ref.current!.getBoundingClientRect();

    if (top === 0) {
      this.setState({ axisZ: true });
    } else {
      this.setState({ axisZ: false });
    }
  }

  activeAnchor = (index: number) => this.setState(({ active: index }));

  render = () => {
    const { anchors } = this.props;
    const { active, axisZ } = this.state;

    return (
      <React.Fragment>
        <Smooth />
        <Navigation ref={this.ref} axisZ={axisZ}>
          <ul>
            {anchors.map((anchor, index) => (
              <li key={anchor.id}>
                <a
                  href={`#${anchor.id}`}
                  onClick={() =>this.activeAnchor(index)}
                  className={active === index ? 'active' : ''}
                >
                  {anchor.text}
                </a>
              </li>
            ))}
          </ul>
        </Navigation>
      </React.Fragment>
    )
  }
}