import React from "react";
import { useHistory } from "react-router";
import { templateService } from "services";
import { CampaignTemplateCreateDto } from "types/templates";
import { TemplateBuilderPage } from ".";
import { TemplatePageHeader } from ".";
import "./Templates.scss";
import { templatesUrl } from "constants/dca/templates";
import { UnlayerDesign } from "types/unlayer";

export interface TemplateCreateProps {
  initialTemplate?: UnlayerDesign | undefined;
}

const TemplateCreate: React.FC<TemplateCreateProps> = ({ initialTemplate }) => {
  const router = useHistory();

  const saveTemplate = async (template: CampaignTemplateCreateDto) => {
    const res = await templateService.createTemplate(template);
    if (res) {
      router.push(templatesUrl);
      return true;
    }
    return false;
  };

  const handleBack = () => {
    router.goBack();
  };

  return (
    <div>
      <TemplatePageHeader name="New Template" onBackClick={handleBack} />
      <div className="templates-page">
        <TemplateBuilderPage
          handleGoBack={handleBack}
          handleCreateOrUpdateTemplate={saveTemplate}
          initialTemplate={initialTemplate}
          backButtonText="Cancel"
        />
      </div>
    </div>
  );
};

export default TemplateCreate;
