import React from "react";
import {
  KomiModalChildrenRenderProps,
  LoadingOverlay,
  useKomiModals,
} from "@komi-app/components";
import { useEdcmApprovedDomains } from "pages/AudienceAndCampaigns/Pages/Embed/utils";
import { ApprovedDomainsForm } from "./ApprovedDomainsForm";

export function useEmbedDcmApprovedDomainsSetup() {
  const modals = useKomiModals();

  return {
    open(edcmId?: string) {
      modals.open({
        title: "Add Domains",
        hasCloseButton: true,
        hasHeaderDivider: true,
        maxWidth: "706px",
        children: ({ close, patch }) => (
          <EmbedDcmApprovedDomainsSetup
            close={close}
            patch={patch}
            edcmId={edcmId}
          />
        ),
      });
    },
  };
}

interface EmbedDcmApprovedDomainsSetupProps
  extends KomiModalChildrenRenderProps {
  edcmId?: string;
}

const EmbedDcmApprovedDomainsSetup = ({
  close,
  edcmId,
}: EmbedDcmApprovedDomainsSetupProps) => {
  const { approvedDomains, updateApprovedDomains } =
    useEdcmApprovedDomains(edcmId);

  const { isLoading: isSaving, mutateAsync } = updateApprovedDomains;

  if (isSaving || !approvedDomains) {
    return (
      <LoadingOverlay loading variant="light">
        <div className="height--320"></div>
      </LoadingOverlay>
    );
  }

  return (
    <ApprovedDomainsForm
      defaultApprovedDomains={approvedDomains}
      close={close}
      onApprovedDomainsChange={async (approvedDomains) => {
        if (approvedDomains) {
          await mutateAsync(approvedDomains, {
            onSuccess: close,
          });
        }
      }}
    />
  );
};

export default EmbedDcmApprovedDomainsSetup;
