import React, { useRef, useState, MouseEvent } from "react";
import { TalentButton } from "@komi-app/components";
import { Icon } from "components/Icon";

import classnames from "classnames";
import "./ImportedTemplateUploadStep.scss";

export interface ImportedTemplateUploadStepProps
  extends React.HTMLProps<HTMLDivElement> {
  onTemplateUpload: (html: string) => void;
  onBack: () => void;
}

export const ImportedTemplateUploadStep: React.FC<
  ImportedTemplateUploadStepProps
> = ({ onTemplateUpload, onBack, ...props }) => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [errors, setErrors] = useState({ noHtmlFile: false });

  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (file: File | null) => {
    setErrors({ noHtmlFile: !file || file.type !== "text/html" });

    if (file && file.type === "text/html") setSelectedFile(file);
  };

  // Prevent automatic opening of file
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  // Handle file dropping
  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();

    const files = e.dataTransfer.files;
    handleFileChange(files[0]);
  };

  // Handle upload button click
  const handleUploadClick = (): void => fileInputRef.current?.click();

  // Handle file input changes on upload selection via click
  const handleFileSelectionUpload = (
    e: React.ChangeEvent<HTMLInputElement>
  ): void => {
    const files = e.target.files || [];
    handleFileChange(files[0]);
  };

  const handleNext = async () => {
    if (selectedFile) {
      onTemplateUpload(await selectedFile.text());
    } else {
      setErrors({ noHtmlFile: true });
    }
  };
  const handleBack = () => {
    onBack();
  };

  const handleClearDropzoneValue = (event: MouseEvent<HTMLDivElement>) => {
    event.stopPropagation();
    setSelectedFile(null);
  };

  const classNames = classnames("imported-template--upload");
  const uploadClassNames = classnames(
    "imported-template--upload__dropzone",
    {
      "imported-template--upload__dropzone-error": errors.noHtmlFile,
    },
    selectedFile && "imported-template--upload__dropzone-uploaded"
  );

  return (
    <div
      {...props}
      className={classNames}
      onDrop={handleDrop}
      onDragOver={handleDragOver}
    >
      <div
        className={uploadClassNames}
        onClick={handleUploadClick}
        data-testid="html-file-dropzone"
      >
        <Icon
          className="imported-template--upload__dropzone-icon"
          name={selectedFile ? "blank-page" : "add-blue"}
        />

        <p className="imported-template--upload__dropzone-title">
          {selectedFile ? "Template Uploaded" : "Upload Template"}
        </p>
        <p className="imported-template--upload__dropzone-description">
          {selectedFile
            ? selectedFile.name
            : "Drop your HTML file here to upload"}
        </p>

        <input
          className="imported-template--upload__dropzone-input"
          type="file"
          accept=".html,.htm"
          ref={fileInputRef}
          onChange={handleFileSelectionUpload}
          data-testid="file-input"
        />
        {selectedFile ? (
          <div
            onClick={(e) => handleClearDropzoneValue(e)}
            data-testid="clear-dropzone-button"
          >
            <Icon
              className="imported-template--upload__dropzone-clear-icon"
              name="close"
              width={26}
              height={26}
            />
          </div>
        ) : null}
      </div>
      <p className="imported-template--upload__error">
        {errors.noHtmlFile && "Please upload an HTML file"}
      </p>

      <div className="imported-template--modal__buttons">
        <TalentButton
          className="imported-template--modal__buttons-cancel"
          variant="secondary"
          onClick={handleBack}
        >
          Previous
        </TalentButton>
        <TalentButton
          className="imported-template--modal__buttons-next"
          variant="primary"
          onClick={handleNext}
          disabled={errors.noHtmlFile}
        >
          Import
        </TalentButton>
      </div>
    </div>
  );
};
