import React from "react";
import { Typography } from "@komi-app/components";
import { TemplateDto } from "types/templates";
import "./CampaignTemplatePreview.scss";
import { TemplateBuilderCreateModal } from "../Templates";
import ReactHtmlParser from "react-html-parser";
import { campaignTemplateService, templateService } from "services";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { templateQueryKey } from "../Templates/utils";
import parse from "html-react-parser";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { Element } from "domhandler";
import TemplateWithCursorGalleryModal from "./Modals/TemplateGalleryModal";

export interface CampaignTemplatePreviewProps {
  templateId: string | null;
  onTemplateSelected: (template: string) => void;
  onCancel: () => void;
  onOpen: () => void;
}

const CampaignTemplatePreview = ({
  templateId,
  onTemplateSelected,
  onCancel,
  onOpen,
}: CampaignTemplatePreviewProps) => {
  const templateSelected = Boolean(templateId);

  const { data: templates } = useQuery(["allTemplates"], () => {
    // NOTE: templates is only used for the disabled state, so this is safe to do
    return templateService.getTemplatesWithCursor(
      {
        cursor: null,
        limit: 12,
        offset: 0,
        cutoff: Date.now(),
        direction: "DESC",
      },
      "",
    );
  });

  const { data: template } = useQuery(
    templateQueryKey(templateId),
    () => {
      return campaignTemplateService.getCampaignTemplate(String(templateId));
    },
    {
      enabled: templateSelected,
    },
  );
  const queryClient = useQueryClient();

  const handleTemplateSelected = (selectedTemplate: TemplateDto) => {
    queryClient.setQueryData(
      templateQueryKey(selectedTemplate.templateId),
      selectedTemplate,
    );
    onTemplateSelected(selectedTemplate.templateId);
  };

  return (
    <>
      {templateSelected ? (
        <div className="campaign-preview">
          {template && (
            <div>
              <RenderTemplate templateHtml={template.templateHtml} />
            </div>
          )}
        </div>
      ) : (
        <div className="select-template">
          <div className="container">
            <Typography.Heading level={4}>Select Template</Typography.Heading>
            <div className="action-buttons">
              <TemplateWithCursorGalleryModal
                allowTemplateImport={false}
                onTemplateSelected={handleTemplateSelected}
                onCancel={onCancel}
                buttonType="button"
                disabled={!templates?.length}
                onOpen={onOpen}
              />
              <TemplateBuilderCreateModal
                onTemplateSelected={handleTemplateSelected}
                onCancel={onCancel}
                onOpen={onOpen}
              />
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default CampaignTemplatePreview;

interface RenderTemplateProps {
  templateHtml: string;
}

const RenderTemplate = ({ templateHtml }: RenderTemplateProps) => {
  return (
    <>
      {parse(templateHtml, {
        replace: (domNode) => {
          // Remove svg's since they won't render in the final email
          if (domNode instanceof Element && domNode.name === "svg") {
            return <></>;
          }
        },
      })}
    </>
  );
};
