import React from 'react';

import { ViewportType, AnnotationType } from '../../constants/type';
import AnnotationSelector from '../AnnotationSelector';
import Markup from '../Markup';

import {
  Popper,
} from './styled';

type Props = AnnotationType & {
  isCovered: boolean;
  isCollapse: boolean;
  mousePosition: Record<string, any>;
  onUpdate: (data: any) => void;
  onDelete: () => void;
  scale: number;
  viewport: ViewportType;
};

const Annotation: React.FunctionComponent<Props> = ({
  obj_type,
  obj_attr,
  isCovered,
  mousePosition,
  isCollapse,
  onUpdate,
  onDelete,
  scale,
  viewport,
}: any) => {
  const {
    page, position, bdcolor, transparency,
  } = obj_attr;

  const processPosition = (type: string, ele: any): any => {
    switch (type) {
      case 'Squiggly':
        return {
          top: `${viewport.height - ele.top * scale}px`,
          left: `${ele.left * scale}px`,
          width: `${(ele.right - ele.left) * scale}px`,
          height: `${(ele.top - ele.bottom) * scale + 5}px`,
        };
      default:
        return {
          top: `${viewport.height - ele.top * scale}px`,
          left: `${ele.left * scale}px`,
          width: `${(ele.right - ele.left) * scale}px`,
          height: `${(ele.top - ele.bottom) * scale + 2}px`,
        };
    }
  };

  return (
    <>
      {
        position.map((ele: any, index: number) => {
          const pos = processPosition(obj_type, ele);

          return (
            <Markup
              key={`block_${page + index}`}
              position={pos}
              bdcolor={bdcolor}
              opacity={transparency}
              markupType={obj_type}
              isCovered={isCovered}
            />
          );
        })
      }
      {
        !isCollapse ? (
          <Popper position={mousePosition}>
            <AnnotationSelector
              onUpdate={onUpdate}
              onDelete={onDelete}
              colorProps={bdcolor}
              opacityProps={transparency * 100}
            />
          </Popper>
        ) : ''
      }
    </>
  );
};

export default Annotation;
