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

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

export interface CampaignFormProps {
  initialValues: CampaignDto;
  isSubmitting: boolean;
  onSubmit: (values: CampaignDto) => Promise<void>;
}

const CampaignCreatePage = () => {
  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 confirmationModal = useConfirmationModal();
  useUnsavedChangesRedirectionWarning(isUnsaved && !isConfirming);

  const location = useLocation<{ formValues: CampaignFormDto }>();

  const initialValues= location.state?.formValues || {
    name: "",
    subject: "",
    schedule: {
      sendType: SendType.Once,
      startTimestamp: null,
      endTimestamp: null,
      timezone: null,
    },
    templateId: null,
    segmentIds: [],
  }

  const createCampaignMutation = useMutation(
    async (formValues: CampaignFormDto) => {
      const mapped = toUpsertDto(formValues);
      setIsUnsaved(false);
      await campaignService.createCampaign(String(talentProfile?.id), mapped);
    },
    {
      onSuccess: () => {
        router.push(campaignsUrl);
      },
    },
  );

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

    confirmationModal.open({
      className: "confirmation-modal-campaign-create",
      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]);

  return (
    <div className="create-campaign">
      <Prompt when={isUnsaved} message={handleBlockedNavigation} />
      <CampaignPageHeader
        name={"New Campaign"}
        onBackClick={() => router.push(campaignsUrl)}
        status={CampaignStatuses.DRAFT}
      />
      <CampaignForm
        initialValues={initialValues}
        onSubmit={async (formValues) => {
          await createCampaignMutation.mutateAsync(formValues);
        }}
        isLoading={createCampaignMutation.isLoading}
        handleUnsavedChanges={handleUnsavedChanges}
      />
    </div>
  );
};

export default CampaignCreatePage;
