import React, { useMemo, useState } from "react";
import { ImportedTemplateModal } from "./TemplateImport/ImportedTemplateModal/ImportedTemplateModal";

import { templateService } from "services";

import { useConfirmationModal } from "@komi-app/components";
import { useHistory } from "react-router";

import { CampaignTemplate, TemplateMenuOptions } from "types/templates";

import { createTemplateEditUrl } from "utils/dca/templates";

import { dcaBaseUrl, dcaSystemTemplatesUrl } from "constants/dca";

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

const TemplatesWithCursor = () => {
  const router = useHistory();

  const [searchTerm, setSearchTerm] = useState("");

  const {
    data,
    reset,
    currentPageIndex,
    pageCount,
    changePageIndex,
    isLoading,
  } = useTemplatesListPagination(searchTerm);
  const isSystemTemplatesVisible = useFeatureIsOn(
    FLAGS.FEAT_CRM_1284_SYSTEM_TEMPLATES,
  );

  const [isImportModalVisible, setIsImportModalVisible] = useState(false);

  const confirmationModal = useConfirmationModal();

  const handleSearchTermUpdate = (searchTerm: string) => {
    setSearchTerm(searchTerm);
  };

  const handleTemplateMenuClicked = async (
    option: any,
    template: CampaignTemplate,
  ) => {
    switch (option.label) {
      case TemplateMenuOptions.Delete:
        confirmationModal.open({
          title: "Are you sure you want to delete this template?",
          description: "This action is not reversible.",
          minWidth: "520px",
          onConfirm: async () => {
            await templateService.deleteTemplate(template.id, template.name);
            // Clears the query cache and forces a it to get again
            reset();
          },

          buttons: [
            {
              label: "Delete",
              action: "confirm",
              variant: "primary",
            },
            {
              label: "Cancel",
              action: "cancel",
              variant: "secondary",
            },
          ],
        });
        break;
      case TemplateMenuOptions.Duplicate:
        await templateService.createTemplate({
          ...template,
          name: `Copy of ${template.name}`,
        });
        // Clears the query cache and forces a it to get again
        reset();
        break;
      case TemplateMenuOptions.Edit:
        reset();
        router.push(createTemplateEditUrl(template.id));
        break;
    }
  };

  const templates = useMemo(() => {
    return data.map((x) => {
      const mappedTemplate: CampaignTemplate = {
        id: x.templateId,
        name: x.name,
        templateJson: x.templateJson,
        templateHtml: x.templateHtml,
        thumbnailUrl: x.thumbnailUrl,
        address: x.address,
      };
      return mappedTemplate;
    });
  }, [data, searchTerm]);

  const handleTemplateNewClick = () => {
    if (isSystemTemplatesVisible) router.push(dcaSystemTemplatesUrl);
    else router.push(`${dcaBaseUrl}/templates-create`);
  };
  const handleTemplateImportClick = () => {
    setIsImportModalVisible(true);
  };
  const handleTemplateModalClose = () => {
    setIsImportModalVisible(false);
  };

  return (
    <div className="templates-page">
      <TemplateWithCursorGalleryPage
        templates={templates}
        pageIndex={currentPageIndex}
        pageCount={pageCount}
        onTemplateImportClick={handleTemplateImportClick}
        onTemplateNewClick={handleTemplateNewClick}
        onTemplateMenuOptionClick={handleTemplateMenuClicked}
        onSearchTermChange={handleSearchTermUpdate}
        onPageIndexChange={changePageIndex}
        selectMode={false}
        isLoading={isLoading}
      />
      <ImportedTemplateModal
        visible={isImportModalVisible}
        onCancel={handleTemplateModalClose}
      />
    </div>
  );
};

export default TemplatesWithCursor;
