import {
  Modal,
  TalentButton,
  useConfirmationModal,
} from "@komi-app/components";
import React, { useState } from "react";
import { CampaignTemplateCreateDto, TemplateDto } from "types/templates";
import { campaignTemplateService } from "services";
import { TemplateBuilderPage } from "..";

export interface TemplateBuilderCreateModalProps {
  onTemplateSelected: (template: TemplateDto) => void;
  onCancel: () => void;
  onOpen: () => void;
}

const TemplateBuilderCreateModal = ({
  onTemplateSelected,
  onCancel,
  onOpen,
}: TemplateBuilderCreateModalProps) => {
  const [modalOpen, setModalOpen] = useState(false);
  const confirmationModal = useConfirmationModal();

  const renderConfirmationModal = () => {
    confirmationModal.open({
      className: "confirmation-modal-campaign-create",
      title: "Are you sure you want to leave this page?",
      description: "Any changes made to this template will be lost.",
      onConfirm: () => {
        setModalOpen(false);
        onCancel();
      },
      buttons: [
        {
          label: "Leave",
          action: "confirm",
          variant: "primary",
        },
        {
          label: "Cancel",
          action: "cancel",
          variant: "secondary",
        },
      ],
    });
  };

  const saveTemplate = async (template: CampaignTemplateCreateDto) => {
    const createdTemplate =
      await campaignTemplateService.createCampaignTemplate(template);

    if (!createdTemplate) return false;

    onTemplateSelected(createdTemplate);
    setModalOpen(false);

    return true;
  };

  function handleNewTemplateClick() {
    setModalOpen(true);
    onOpen();
  }

  return (
    <>
      <TalentButton variant="secondary" onClick={handleNewTemplateClick}>
        NEW TEMPLATE
      </TalentButton>

      <Modal
        width={1200}
        className="komi-modal"
        visible={modalOpen}
        onCancel={renderConfirmationModal}
        title="New Template"
      >
        <TemplateBuilderPage
          handleGoBack={renderConfirmationModal}
          handleCreateOrUpdateTemplate={saveTemplate}
          backButtonText="Cancel"
          disablePrompt={true}
        />
      </Modal>
    </>
  );
};

export default TemplateBuilderCreateModal;
