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

import Divider from '../Divider';
import Markup from '../Markup';
import { scrollIntoView } from '../../helpers/utility';

import {
  PageNumber, AnnotationBox, Content, Inner, Text,
} from './styled';

type Props = {
  type: string;
  page?: number;
  bdcolor: string;
  getText: () => Promise<any>;
  showPageNum?: boolean;
  transparency: number;
}

const AnnotationItem = ({
  type,
  page,
  showPageNum,
  bdcolor,
  getText,
  transparency,
}: Props): React.ReactElement => {
  const [content, setContent] = useState([]);

  const handleClick = (): void => {
    const ele: HTMLElement | null = document.getElementById(`page_${page}`);

    if (ele) {
      scrollIntoView(ele);
    }
  };

  useEffect(() => {
    getText().then((text) => {
      let textArray = [];

      if (text.includes(' ')) {
        textArray = text.split(' ');
      } else {
        textArray = text.match(/.{1,12}/g);
      }

      setContent(textArray);
    });
  }, []);

  return (
    <>
      {showPageNum && <Divider orientation="horizontal" />}
      {showPageNum && <PageNumber>{`Page ${page}`}</PageNumber>}
      <AnnotationBox onClick={handleClick}>
        <Content>
          {
            content.length && content.map((textContent: string, index: number): any => {
              const key = `key_${index}`;
              return textContent ? (
                <Inner key={key}>
                  <Text>{textContent}</Text>
                  <Markup
                    position={{
                      top: 0, left: 0, width: '100%', height: '100%',
                    }}
                    markupType={type}
                    bdcolor={bdcolor}
                    opacity={transparency}
                  />
                </Inner>
              ) : null;
            })
          }
        </Content>
      </AnnotationBox>
    </>
  );
};

export default AnnotationItem;
