import React, { useEffect } from "react";
import {
  TemplatePromptModal,
} from "@komi-app/creator-ui";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import selfless from "@komi-app/selfless";
import When from "@komi-app/when";
import { useHasModulesOnInit } from "./useHasModulesOnInit";
import { useAnalytics } from "hooks/useAnalytics";
import { SEGMENT_EVENTS } from "constants/segment";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";

export interface TemplateSelectionModalV2Props {
  onStartFromScratch?: () => void;
  onStartWithTemplates?: () => void;
}

interface ViewProps {
  onStartFromScratch?: () => void;
  onStartWithTemplates?: () => void;
  showModal: boolean;
}

const useTemplateSelectionModalV2 = ({
  onStartFromScratch,
  onStartWithTemplates,
}: TemplateSelectionModalV2Props) => {
  const { sendSegmentEvent } = useAnalytics();
  const shouldShowModuleMenu = useFeatureIsOn(
    FLAGS.FEAT_SB_358_SHOW_MODULE_MENU_AFTER_NO_TEMPLATE
  );
  const hasModules = useHasModulesOnInit();
  const showModal = !hasModules;
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const viewGoalTemplateModal = createTracker(CreatorEvent.VIEW_GOAL_TEMPLATE_MODAL)

  useEffect(() => {
    if (showModal) {
      useAnalyticsSDK
        ? viewGoalTemplateModal()
        : sendSegmentEvent(SEGMENT_EVENTS.VIEW_GOAL_TEMPLATE_MODAL);
    }
  }, [showModal]);

  return {
    onStartFromScratch: shouldShowModuleMenu ? onStartFromScratch : undefined,
    onStartWithTemplates,
    showModal,
  };
};

const View = ({
  onStartFromScratch,
  onStartWithTemplates,
  showModal,
}: ViewProps) => (
  <When
    value={showModal}
    then={
      <TemplatePromptModal
        onStartFromScratch={onStartFromScratch}
        onStartWithTemplates={onStartWithTemplates}
      />
    }
  />
);

export const TemplateSelectionModalV2 = selfless(
  View,
  useTemplateSelectionModalV2
);
