import React, { useState } from "react";
import {
  Modal,
  TalentButtonWithIcon,
  useConfirmationModal,
} from "@komi-app/components";
import { CampaignTemplateCreateDto, TemplateDto } from "types/templates";
import { campaignTemplateService } from "services";
import { TemplateBuilderPage } from "..";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { templateQueryKey } from "../utils";

export interface CampaignTemplateBuilderEditModalProps {
  templateId: string;
  onOpen: () => void;
}

const CampaignTemplateBuilderEditModal = ({
  templateId,
  onOpen,
}: CampaignTemplateBuilderEditModalProps) => {

  const [modalOpen, setModalOpen] = useState(false);
  const query = useQueryClient();
  const confirmationModal = useConfirmationModal();

  const renderConfirmationModal = () => {
    if (!modalOpen) return;

    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);
        cancel();
      },
      buttons: [
        {
          label: "Leave",
          action: "confirm",
          variant: "primary",
        },
        {
          label: "Cancel",
          action: "cancel",
          variant: "secondary",
        },
      ],
    });
  };

  const { data: template } = useQuery(["getTemplate", templateId], () =>
    campaignTemplateService.getCampaignTemplate(templateId).then((res) => {
      return res as TemplateDto;
    }),
  );

  const updateTemplate = async (template: CampaignTemplateCreateDto) => {
    const res = await campaignTemplateService.updateCampaignTemplate(
      templateId,
      template,
    );
    if (!res) return false;

    query.invalidateQueries({ queryKey: templateQueryKey(templateId) });
    setModalOpen(false);

    return true;
  };

  function cancel() {
    setModalOpen(false);
  }

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

  return (
    <>
      <TalentButtonWithIcon
        type="text"
        label="Edit"
        prefixIcon="pencil"
        onClick={handleOpen}
      />
      <Modal
        width={1200}
        className="komi-modal"
        visible={modalOpen}
        onCancel={renderConfirmationModal}
        title="Edit Email Content"
      >
        {modalOpen && (
          <TemplateBuilderPage
            existingTemplate={template}
            isCampaignTemplate
            handleGoBack={renderConfirmationModal}
            handleCreateOrUpdateTemplate={updateTemplate}
            backButtonText="Close"
          />
        )}
      </Modal>
    </>
  );
};

export default CampaignTemplateBuilderEditModal;
