import React, { useCallback, useEffect, useState } from 'react';
import { Upload, Tooltip, Popover, Modal, Progress, Spin, Result } from 'antd';
import * as AntdIcons from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import './style.less';

const allIcons: { [key: string]: any } = AntdIcons;

const { Dragger } = Upload;
interface AntdIconClassifier {
  load: () => void;
  predict: (imgEl: HTMLImageElement) => void;
}
declare global {
  interface Window {
    antdIconClassifier: AntdIconClassifier;
  }
}

interface PicSearcherState {
  loading: boolean;
  modalOpen: boolean;
  popoverVisible: boolean;
  icons: iconObject[];
  fileList: any[];
  error: boolean;
  modelLoaded: boolean;
}

interface iconObject {
  type: string;
  score: number;
}

const PicSearcher: React.FC = () => {
  const intl = useIntl();
  const {formatMessage} = intl;
  const [state, setState] = useState<PicSearcherState>({
    loading: false,
    modalOpen: false,
    popoverVisible: false,
    icons: [],
    fileList: [],
    error: false,
    modelLoaded: false,
  });
  const predict = (imgEl: HTMLImageElement) => {
    try {
      let icons: any[] = window.antdIconClassifier.predict(imgEl);
      if (gtag && icons.length) {
        gtag('event', 'icon', {
          event_category: 'search-by-image',
          event_label: icons[0].className,
        });
      }
      icons = icons.map(i => ({ score: i.score, type: i.className.replace(/\s/g, '-') }));
      setState(prev => ({ ...prev, loading: false, error: false, icons }));
    } catch {
      setState(prev => ({ ...prev, loading: false, error: true }));
    }
  };
  // eslint-disable-next-line class-methods-use-this
  const toImage = (url: string) =>
    new Promise(resolve => {
      const img = new Image();
      img.setAttribute('crossOrigin', 'anonymous');
      img.src = url;
      img.onload = () => {
        resolve(img);
      };
    });

  const uploadFile = useCallback((file: File) => {
    setState(prev => ({ ...prev, loading: true }));
    const reader = new FileReader();
    reader.onload = () => {
      toImage(reader.result as string).then(predict);
      setState(prev => ({
        ...prev,
        fileList: [{ uid: 1, name: file.name, status: 'done', url: reader.result }],
      }));
    };
    reader.readAsDataURL(file);
  }, []);

  const onPaste = useCallback((event: ClipboardEvent) => {
    const items = event.clipboardData && event.clipboardData.items;
    let file = null;
    if (items && items.length) {
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.includes('image')) {
          file = items[i].getAsFile();
          break;
        }
      }
    }
    if (file) {
      uploadFile(file);
    }
  }, []);
  const toggleModal = useCallback(() => {
    setState(prev => ({
      ...prev,
      modalOpen: !prev.modalOpen,
      popoverVisible: false,
      fileList: [],
      icons: [],
    }));
    if (!localStorage.getItem('disableIconTip')) {
      localStorage.setItem('disableIconTip', 'true');
    }
  }, []);

  useEffect(() => {
    const script = document.createElement('script');
    script.onload = async () => {
      await window.antdIconClassifier.load();
      setState(prev => ({ ...prev, modelLoaded: true }));
      document.addEventListener('paste', onPaste);
    };
    script.src = 'https://cdn.jsdelivr.net/gh/lewis617/antd-icon-classifier@0.0/dist/main.js';
    document.head.appendChild(script);
    setState(prev => ({ ...prev, popoverVisible: !localStorage.getItem('disableIconTip') }));
    return () => {
      document.removeEventListener('paste', onPaste);
    };
  }, []);

  return (
    <div className="iconPicSearcher">
      <Popover
        open={state.popoverVisible}
      >
        <AntdIcons.CameraOutlined className="icon-pic-btn" onClick={toggleModal} />
      </Popover>
    </div>
  );
};

export default PicSearcher;
