import React, { useState, useCallback } from "react";
import { HtmlCodeEditor } from "../../HtmlCodeEditor";
import { TalentButton } from "@komi-app/components";
import notification from "utils/notification";
import classnames from "classnames";
import "./ImportedTemplateEditorStep.scss";
import "../../HtmlCodeEditor/HtmlCodeEditor.scss";

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

export const ImportedTemplateEditorStep: React.FC<
  ImportedTemplateEditorStepProps
> = ({ onBack, onTemplateUpload, ...props }) => {
  const [html, setHtml] = useState("");
  const [isValidHtml, setIsValidHtml] = useState(false);

  const handleHtmlChange = (updatedHtml: string) => setHtml(updatedHtml);
  const handleValidateHtml = (isValid: boolean) => setIsValidHtml(isValid);
  const handleBack = () => onBack();

  const handleTemplateUpload = useCallback(() => {
    if (html !== "") {
      onTemplateUpload(html);
    }
  }, [isValidHtml, html]);

  const classNames = classnames("imported-template--code");

  return (
    <div {...props} className={classNames}>
      <HtmlCodeEditor
        className="imported-template--code__editor"
        html={html}
        isErrorPaneVisible={false}
        onHtmlChange={handleHtmlChange}
        validateHtml={handleValidateHtml}
      />

      <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={handleTemplateUpload}
        >
          Import
        </TalentButton>
      </div>
    </div>
  );
};
