import React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useHistory } from "react-router";
import { templateService } from "services";
import { CampaignTemplateCreateDto, TemplateDto } from "types/templates";
import { TemplateBuilderPage } from ".";
import { TemplatePageHeader } from ".";
import { templatesUrl } from "constants/dca/templates";
import { dcaBaseUrl } from "constants/dca";

import "./Templates.scss";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";

export interface TemplateEditProps {
  templateId: string;
  campaignId?: string;
}

export const TemplateEdit = ({ templateId, campaignId }: TemplateEditProps) => {
  const router = useHistory();
  const query = useQueryClient();

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

  const backLink = campaignId
    ? // FLAG
      `${dcaBaseUrl}/campaign-edit?campaignId=${campaignId}`
    : templatesUrl;

  const updateTemplate = async (template: CampaignTemplateCreateDto) => {
    const res = await templateService.updateTemplate(templateId, template);
    if (res) {
      await query.invalidateQueries({ queryKey: ["getTemplate"] });
      return true;
    }
    return false;
  };

  return (
    <div>
      {template && (
        <>
          <TemplatePageHeader
            name={template.name}
            onBackClick={() => router.push(backLink)}
          />

          <div className="templates-page">
            <TemplateBuilderPage
              existingTemplate={template}
              handleGoBack={() => router.push(backLink)}
              handleCreateOrUpdateTemplate={updateTemplate}
              backButtonText="Back"
            />
          </div>
        </>
      )}
    </div>
  );
};

export default TemplateEdit;
