import {
  Modal,
  TalentButton,
  TalentButtonWithIcon,
  useConfirmationModal,
  Typography,
} from "@komi-app/components";
import React, { useMemo, useState } from "react";
import { CampaignTemplate, TemplateDto } from "types/templates";
import "./Modal.scss";
import { campaignTemplateService } from "services";
import TemplateWithCursorGalleryPage from "../../Templates/TemplateGalleryPage/TemplateWithCursorGalleryPage";
import { useTemplatesListPagination } from "../../Templates/utils";

export interface TemplateGalleryProps {
  allowTemplateImport?: boolean;
  onTemplateSelected: (template: TemplateDto) => void;
  onCancel: () => void;
  buttonType: "button" | "text";
  disabled: boolean;
  onOpen: () => void;
}

const TemplateWithCursorGalleryModal = ({
  allowTemplateImport = true,
  onTemplateSelected,
  onCancel,
  buttonType,
  disabled,
  onOpen,
}: TemplateGalleryProps) => {
  const [modalOpen, setModalOpen] = useState(false);
  const confirmationModal = useConfirmationModal();

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

  const { data, currentPageIndex, pageCount, changePageIndex, isLoading } =
    useTemplatesListPagination(searchTerm, {
      limit: 12,
    });

  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]);

  const onSelected = async (template: CampaignTemplate) => {
    const campaignTemplate =
      await campaignTemplateService.createCampaignTemplate(template);
    if (!campaignTemplate) return;
    onTemplateSelected(campaignTemplate);
    setModalOpen(false);
  };

  function cancel() {
    setModalOpen(false);
    onCancel();
  }

  return (
    <>
      {buttonType === "text" ? (
        <TalentButtonWithIcon
          type="text"
          label="Change Template"
          prefixIcon="rotation"
          onClick={() =>
            confirmationModal.open({
              title: "Are you sure you want to change template?",
              minWidth: 520,
              maxWidth: 520,
              description:
                "Any changes made to the email content will be lost.",
              buttons: [
                {
                  label: "Continue",
                  variant: "primary",
                  action: "confirm",
                },
                {
                  label: "Cancel",
                  variant: "secondary",
                  action: "cancel",
                },
              ],
              onConfirm: () => {
                setModalOpen(true);
                onOpen();
              },
              fullWidthButtons: false,
            })
          }
        />
      ) : (
        <TalentButton
          disabled={disabled}
          variant="secondary"
          onClick={() => {
            setModalOpen(true);
            onOpen();
          }}
        >
          FROM GALLERY
        </TalentButton>
      )}
      <Modal
        width={1000}
        className="komi-modal"
        visible={modalOpen}
        onCancel={cancel}
        title="Select Template"
      >
        <Typography.Heading level={4}></Typography.Heading>
        <TemplateWithCursorGalleryPage
          allowTemplateImport={allowTemplateImport}
          templates={templates}
          pageIndex={currentPageIndex}
          pageCount={pageCount}
          onSearchTermChange={(searchTerm) => setSearchTerm(searchTerm)}
          onPageIndexChange={changePageIndex}
          isLoading={isLoading}
          onTemplateImportClick={() => {}}
          onTemplateMenuOptionClick={() => {}}
          onTemplateNewClick={() => {}}
          onTemplateSelected={onSelected}
          selectMode
          disabled={disabled}
        />
      </Modal>
    </>
  );
};

export default TemplateWithCursorGalleryModal;
