import React from 'react';
import queryString from 'query-string';

import { AnnotationType } from '../../constants/type';
import Icon from '../Icon';
import { downloadFileWithUri, uploadFile } from '../../helpers/utility';
import { parseAnnotationFromXml } from '../../helpers/annotation';

import { Separator } from '../../global/otherStyled';
import {
  Head, IconWrapper,
} from '../../global/sidebarStyled';

type Props = {
  close: () => void;
  addAnnots: (annotations: AnnotationType[]) => void;
  hasAnnots: boolean;
};

const index: React.FC<Props> = ({
  close,
  addAnnots,
  hasAnnots,
}: Props) => {
  const handleExport = (): void => {
    if (hasAnnots) {
      const parsed = queryString.parse(window.location.search);
      const uri = `/api/v1/output.xfdf?f=${parsed.token}`;
      downloadFileWithUri('output.xfdf', uri);
    }
  };

  const handleImport = (): void => {
    uploadFile('.xfdf').then((data) => {
      const annotations = parseAnnotationFromXml(data);
      addAnnots(annotations);
    });
  };

  return (
    <Head>
      <IconWrapper>
        <Icon glyph="right-back" onClick={close} />
      </IconWrapper>
      <Separator />
      <IconWrapper>
        <Icon glyph="sort" />
      </IconWrapper>
      <IconWrapper onClick={handleExport}>
        <Icon
          glyph="annotation-export"
          isDisabled={!hasAnnots}
        />
      </IconWrapper>
      <IconWrapper onClick={handleImport}>
        <Icon glyph="import" />
      </IconWrapper>
    </Head>
  );
};

export default index;
