import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import Typography from '../Typography';
import Item from '../AnnotationItem';

import { Body } from '../../global/sidebarStyled';

type Props = {
  isActive: boolean;
  annotations: AnnotationType[];
};

const AnnotationList: React.FC<Props> = ({
  isActive = false,
  annotations,
}: Props) => {
  const { t } = useTranslation('sidebar');
  const [list, setList] = useState<AnnotationType[]>([]);

  useEffect(() => {
    if (isActive) {
      const tmpArray = [...annotations];
      tmpArray.sort((a, b) => {
        if (a.obj_attr.page > b.obj_attr.page) {
          return 1;
        }
        if (a.obj_attr.page < b.obj_attr.page) {
          return -1;
        }
        return 0;
      });
      setList(tmpArray);
    }
  }, [isActive, annotations]);

  return (
    <Body>
      <div>
        <Typography light align="left">
          {`${annotations.length} ${t('annotation')}`}
        </Typography>
        {isActive &&
          list.map((ele, index) => {
            const key = `annotation_item_${index}`;
            const {
              obj_type,
              obj_attr: { page, title, date, style },
            } = ele;
            const actualPage = page + 1;
            const prevAnnot = list[index - 1];
            const prevPage =
              index > 0 && prevAnnot ? prevAnnot.obj_attr.page + 1 : -1;

            let annotType = obj_type;
            if (obj_type === 'checkbox' && style === '1') {
              annotType = 'radio';
            }

            return (
              <Item
                key={key}
                title={title}
                date={date}
                type={annotType}
                page={actualPage}
                showPageNum={actualPage !== prevPage}
              />
            );
          })}
      </div>
    </Body>
  );
};

export default AnnotationList;
