import React, { useState, useEffect } from "react";
import { CampaignStatuses, useConfirmationModal } from "@komi-app/components";
import { Prompt, useHistory } from "react-router-dom";
import { Location } from "history";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTypedSelector } from "redux/rootReducer";
import { selectTalentProfile } from "redux/User/selector";
import { campaignService } from "services";
import CampaignPageHeader from "../CampaignPageHeader";
import { CampaignFormDto } from "../CampaignForm/types";
import { toFormDto, toUpsertDto } from "../CampaignForm/mappers";
import CampaignForm from "../CampaignForm/CampaignForm";
import CampaignMenu from "../CampaignMenu";
import { toCampaignStatuses } from "utils/dca/campaigns";
import { campaignsUrl } from "constants/dca/campaigns";
import { Campaign } from "types/campaigns";
import { useUnsavedChangesRedirectionWarning } from "hooks/useUnsavedChangesRedirectionWarning";

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

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

const CampaignUpdatePage = ({ campaignId }: CampaignUpdatePageProps) => {
  const router = useHistory();
  const talentProfile = useTypedSelector(selectTalentProfile);
  const [isUnsaved, setIsUnsaved] = useState(false);
  const [isConfirming, setIsConfirming] = useState(false);
  const [navigatingLocation, setNavigatingLocation] = useState<string | null>(
    null,
  );

  const isCampaignMenuDisabled = useFeatureIsOn(
    FLAGS.FIX_CRM_1246_EMAIL_CAMPAIGN_EDIT_STOP_REMOVAL,
  );

  const confirmationModal = useConfirmationModal();
  useUnsavedChangesRedirectionWarning(isUnsaved && !isConfirming);

  const { data: existingCampaign } = useQuery(
    ["campaigns", campaignId],
    async () => {
      const result = await campaignService.getCampaign(
        String(talentProfile?.id),
        campaignId,
      );
      return result;
    },
    {
      cacheTime: 0,
      refetchOnWindowFocus: false,
    },
  );

  const updateCampaignMutation = useMutation(
    async (formValues: CampaignFormDto) => {
      const mapped = toUpsertDto(formValues);
      await campaignService.updateCampaign(
        String(talentProfile?.id),
        campaignId,
        mapped,
      );
    },
    {
      onSuccess: () => router.push(campaignsUrl),
    },
  );

  const renderConfirmationModal = () => {
    setIsConfirming(true);

    confirmationModal.open({
      className: "confirmation-modal-campaign-update",
      title: "Are you sure you want to leave this page?",
      description: "Any changes made to this campaign will be lost.",
      onConfirm: () => {
        setIsUnsaved(false);
      },
      onCancel: () => {
        setIsConfirming(false);
      },
      buttons: [
        {
          label: "Leave",
          action: "confirm",
          variant: "primary",
        },
        {
          label: "Cancel",
          action: "cancel",
          variant: "secondary",
        },
      ],
    });
  };

  const handleUnsavedChanges = (value: boolean) => {
    setIsUnsaved(value);
  };

  const handleBlockedNavigation = (nextLocation: Location<unknown>) => {
    if (isUnsaved) {
      setNavigatingLocation(nextLocation.pathname);
      renderConfirmationModal();
    }
    // Allow navigation if there are no unsaved changes
    return !isUnsaved;
  };

  useEffect(() => {
    if (!isUnsaved && navigatingLocation) {
      // Navigate to the previous blocked location with your navigate function
      window.location.href = navigatingLocation;
    }
  }, [isUnsaved, navigatingLocation]);

  const status = (campaign: Campaign): CampaignStatuses => {
    return toCampaignStatuses(
      campaign.status,
      campaign.schedule.startTimestamp,
    );
  };

  const hasCampaignMenu = !isCampaignMenuDisabled && existingCampaign;

  return (
    <div className="create-campaign">
      <Prompt when={isUnsaved} message={handleBlockedNavigation} />
      <CampaignPageHeader
        name={existingCampaign?.name ?? ""}
        onBackClick={() => router.push(campaignsUrl)}
        status={existingCampaign ? status(existingCampaign) : null}
        menu={
          hasCampaignMenu ? (
            <CampaignMenu
              campaignId={campaignId}
              campaignName={existingCampaign.name}
              campaignStatus={status(existingCampaign)}
              omitEditOption
            />
          ) : undefined
        }
      />
      {existingCampaign && (
        <CampaignForm
          initialValues={toFormDto(existingCampaign)}
          onSubmit={async (formValues) => {
            await updateCampaignMutation.mutateAsync(formValues);
          }}
          isLoading={updateCampaignMutation.isLoading}
          campaignId={campaignId}
          handleUnsavedChanges={handleUnsavedChanges}
        />
      )}
    </div>
  );
};

export default CampaignUpdatePage;
