import React, { useState, useEffect } from 'react';
import cn from 'classnames';
import { useDispatch } from '../../app/store';
import styles from './FileDrop.module.css';
import { loadUrl } from './fileSlice';

export function FileDrop() {
  const [activeCounter, setActiveCounter] = useState(0);
  const dispatch = useDispatch();

  useEffect(() => {
    const onDragEnter = (event: DragEvent) => {
      setActiveCounter((counter) => counter + 1);
      event.preventDefault();
      event.stopPropagation();
    };
    document.documentElement.addEventListener('dragenter', onDragEnter);
    return () =>
      document.documentElement.removeEventListener('dragenter', onDragEnter);
  }, []);

  useEffect(() => {
    const onDragOver = (event: DragEvent) => {
      event.preventDefault();
      event.stopPropagation();
    };
    document.documentElement.addEventListener('dragover', onDragOver);
    return () =>
      document.documentElement.removeEventListener('dragover', onDragOver);
  }, []);

  useEffect(() => {
    const onDragLeave = (event: DragEvent) => {
      setActiveCounter((counter) => counter - 1);
      event.preventDefault();
      event.stopPropagation();
    };
    document.documentElement.addEventListener('dragleave', onDragLeave);
    return () =>
      document.documentElement.removeEventListener('dragleave', onDragLeave);
  }, []);

  useEffect(() => {
    const onDrop = (event: DragEvent) => {
      setActiveCounter((counter) => counter - 1);
      if (event.dataTransfer?.files.length !== 1) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      window.history.pushState(
        window.history.state,
        document.title,
        window.location.href
      );
      dispatch(loadUrl(URL.createObjectURL(event.dataTransfer.files[0])));
    };
    document.documentElement.addEventListener('drop', onDrop);
    return () => document.documentElement.removeEventListener('drop', onDrop);
  }, [dispatch]);

  return (
    <div className={cn(styles.outer, activeCounter && styles.active)}>
      <div className={styles.inner}>Drop file here</div>
    </div>
  );
}
