import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { Modal } from "@komi-app/components";

import { ImportedTemplateMethodStep } from "./steps/ImportedTemplateMethodStep";
import { ImportedTemplateUploadStep } from "./steps/ImportedTemplateUploadStep";
import { ImportedTemplateEditorStep } from "./steps/ImportedTemplateEditorStep";

import { createTemplateUrl } from "constants/dca";

import { TemplateImportMethod } from "../types";

import { noop } from "utils/noop";
import { createClassicTemplate } from "../utils";

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

export enum TemplateImportStep {
  Method = "Method",
  UploadFile = "UploadFile",
  PasteInCode = "PasteInCode",
}

export interface ImportedTemplateModalProps
  extends React.HTMLProps<HTMLDivElement> {
  onCancel: () => void;
  visible: boolean;
}

export const ImportedTemplateModal: React.FC<ImportedTemplateModalProps> = ({
  className,
  onCancel = noop,
  ...props
}) => {
  const history = useHistory();
  const [step, setStep] = useState(TemplateImportStep.Method);

  const classNames = classnames(className, "imported-template--modal");

  // Display the next step based on the selected method
  const handleMethodSelection = (method: TemplateImportMethod) => {
    setStep(TemplateImportStep[method]);
  };
  // Pass the uploaded HTML to the create template page
  const handleTemplateUpload = (html: string) => {
    // This is the Unlayer structure for an HTML template
    // The classic flag is used to determine the Unlayer editor type
    const initialTemplate = createClassicTemplate(html);

    history.push({
      pathname: createTemplateUrl,
      state: { initialTemplate },
    });
  };

  // Going back will always take the user back to the method selection step
  const handleBack = () => setStep(TemplateImportStep.Method);

  return (
    <Modal
      {...props}
      title="Import Template"
      onCancel={onCancel}
      className={classNames}
    >
      {step === TemplateImportStep.Method && (
        <ImportedTemplateMethodStep
          onCancel={onCancel}
          onMethodSelected={handleMethodSelection}
        />
      )}
      {step === TemplateImportStep.UploadFile && (
        <ImportedTemplateUploadStep
          onTemplateUpload={handleTemplateUpload}
          onBack={handleBack}
        />
      )}
      {step === TemplateImportStep.PasteInCode && (
        <ImportedTemplateEditorStep
          onTemplateUpload={handleTemplateUpload}
          onBack={handleBack}
        />
      )}
    </Modal>
  );
};
