import { useRef, useState } from "react";
import { CloudArrowUpFill } from "react-bootstrap-icons";
import "./DragAndDrop.css";
import { DialectReportView } from "../../DialectReportView";
import { parseReportData } from "../../data/parseReportData";

export const DragAndDrop = () => {
  const [dragActive, setDragActive] = useState(false);
  const [invalidFile, setInvalidFile] = useState(false);
  const [lines, setLines] = useState();
  const inputRef = useRef(null);

  const handleDragEnter = function (e) {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(true);
  };

  const handleDragLeave = function (e) {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
  };

  const handleDrop = function (e) {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    if (e.dataTransfer?.files?.[0]) {
      const file = e.dataTransfer.files[0];
      handleFiles(file);
    }
  };

  const handleChange = function (e) {
    e.preventDefault();
    e.stopPropagation();
    if (e.target?.files?.[0]) {
      const file = e.target.files[0];
      handleFiles(file);
    }
  };

  const onButtonClick = () => {
    inputRef.current.value = "";
    inputRef.current.click();
  };

  const handleFiles = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const dataObjectsArray = e.target.result.trim().split(/\r?\n/);
        const lines = dataObjectsArray.map((line) => JSON.parse(line));
        setLines(parseReportData(lines));
      } catch (error) {
        setInvalidFile(true);
        setTimeout(() => {
          setDragActive(false);
          setInvalidFile(false);
        }, 4000);
        console.error("Error :", error);
      }
    };
    reader.readAsText(file);
  };

  if (lines) {
    return <DialectReportView reportData={lines} />;
  }

  return (
    <div>
      <div aria-live="polite" aria-atomic="true"></div>
      <div className="card-body d-grid justify-content-center">
        <form
          className="form-file-upload"
          onDragEnter={handleDragEnter}
          onDragOver={handleDragEnter}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          onSubmit={(e) => e.preventDefault()}
        >
          <input
            ref={inputRef}
            type="file"
            id="input-file-upload"
            className="d-none"
            onChange={handleChange}
          />

          <div
            id="label-file-upload"
            className={dragActive ? "drag-active" : ""}
            style={{ backgroundColor: `${invalidFile ? "#f00b0b39" : ""}` }}
          >
            <div className="text-center">
              <CloudArrowUpFill size={80} />
              {invalidFile ? (
                <h5 className={"pt-3 text-danger"}>
                  You're uploading something that wasn't produced by Bowtie!
                </h5>
              ) : (
                <>
                  <p className="card-text">
                    Drag and drop the JSON report file generated by Bowtie in
                    your local repository!
                  </p>
                  <button className="btn btn-primary" onClick={onButtonClick}>
                    Upload report
                  </button>
                </>
              )}
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};
