import React, { useState, useEffect } from 'react';
import queryString from 'query-string';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';

import Icon from '../components/Icon';
import Button from '../components/Button';
import Drawer from '../components/Drawer';
import WatermarkOption from '../components/WatermarkOption';
import useActions from '../actions';
import useStore from '../store';

import { BtnWrapper } from '../global/toolStyled';

const WatermarkTool: React.FC = () => {
  const { t } = useTranslation('sidebar');
  const [isActive, setActive] = useState(false);
  const [{ totalPage, watermark, annotations }, dispatch] = useStore();
  const { setSidebar, updateWatermark, addAnnots, updateAnnots } = useActions(
    dispatch
  );

  const setDataState = (obj: WatermarkType): void => {
    updateWatermark(obj);
  };

  const removeWatermarkInAnnots = (): void => {
    const index = annotations.findIndex(
      (ele: AnnotationType) => ele.obj_type === 'watermark'
    );
    if (index >= 0) {
      annotations.splice(index, 1);
      updateAnnots(annotations);
    }
  };

  const handleClick = (): void => {
    setActive(!isActive);
    setSidebar(!isActive ? 'watermark' : '');
  };

  const handleSave = (): void => {
    const { type, imagepath = '', ...rest } = watermark;
    const imagePathMatch = imagepath.match(/image\/(.*);base64/) || [];
    const imageTypeMatch = imagepath.match(/base64,(.*)/) || [];

    const watermarkData = {
      obj_type: 'watermark',
      obj_attr: {
        ...rest,
        type,
        pages: `0-${totalPage}`,
        opacity: watermark.opacity,
        original_image_name: imagePathMatch && `temp.${imagePathMatch[1]}`,
        image_data: imageTypeMatch && imageTypeMatch[1],
      },
    };

    removeWatermarkInAnnots();
    addAnnots([watermarkData]);
  };

  const handleDelete = (): void => {
    removeWatermarkInAnnots();
    updateWatermark({
      ...watermark,
      text: '',
      imagepath: '',
    });
  };

  useEffect(() => {
    const parsed = queryString.parse(window.location.search);

    if (parsed.watermark) {
      const datetime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      setDataState({
        text: `${parsed.watermark} @ ${datetime}`,
      });
    }
  }, []);

  return (
    <>
      <BtnWrapper>
        <Button shouldFitContainer align="left" onClick={handleClick}>
          <Icon glyph="watermark" style={{ marginRight: '10px' }} />
          {t('watermark')}
        </Button>
      </BtnWrapper>
      <Drawer open={isActive} anchor="left" zIndex={4}>
        <WatermarkOption
          isActive={isActive}
          onClick={handleClick}
          onSave={handleSave}
          onDelete={handleDelete}
          setDataState={setDataState}
          {...watermark}
        />
      </Drawer>
    </>
  );
};

export default WatermarkTool;
