import ConfirmDeleteModal from "components/ConfirmDeleteModal";
import DataCaptureFormCard from "components/DataCaptureFormCard";
import DataCaptureModal from "components/DataCaptureModal";
import { Paragraph } from "components/Typography";
import { SEGMENT_EVENTS } from "constants/segment";
import { useAnalytics } from "hooks/useAnalytics";
import { useModules } from "hooks/useModules";
import {
  DataCaptureFormItem,
  TalentProfileModule,
} from "models/talent/talent-profile-module.model";
import React, { useCallback, useMemo, useState } from "react";
import { DraggableProvidedDragHandleProps } from "react-beautiful-dnd";
import { useHistory } from "react-router-dom";
import { useTypedSelector } from "redux/rootReducer";
import { selectLocalizationSelected } from "redux/User/selector";
import { ArrayServices } from "utils/array";
import { isEmptyModule } from "utils/modules";
import ModuleEditor from "../ModuleEditor";
import EmptyModule from "./EmptyModule";
import "./ModuleDataCaptureForm.scss";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { DataCaptureFormType } from "@komi-app/shared-types";
import { useCreatorTracking, CreatorEvent } from "@komi-app/analytics-sdk";
import { trackingProps } from "utils/tracking";

interface ModuleDataCaptureFromProps {
  module: TalentProfileModule<DataCaptureFormItem>;
  dragHandleProps?: DraggableProvidedDragHandleProps;
}

const ModuleDataCaptureFrom: React.FC<ModuleDataCaptureFromProps> = ({
  module,
  dragHandleProps,
}) => {
  const { sendSegmentEvent } = useAnalytics();
  const router = useHistory();
  const profileContext = useModules();
  const [visibleDelete, setVisibleDelete] = useState(false);
  const [visibleEditor, setVisibleEditor] = useState(false);
  const localizationSelected = useTypedSelector(selectLocalizationSelected);
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT);
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED);

  const item: any = useMemo(() => {
    return module.items[0];
  }, [module.items]);

  const isContactFormFlagOn = useFeatureIsOn(FLAGS.FEAT_SB_630_CONTACT_FORM);
  const isContactForm =
    isContactFormFlagOn && item?.formType === DataCaptureFormType.CONTACT_FORM;

  const onDeleteItem = useCallback(() => {
    profileContext.setModule?.({
      ...module,
      items: [],
      isUpdate: true,
    });
    setVisibleDelete(false);
  }, [module, profileContext.setModule]);

  const onSaveModule = useCallback(
    (dataForm: DataCaptureFormItem) => {
      let moduleEdit;
      if (item) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(module.items, 0, {
            ...module.items[0],
            ...dataForm,
          }),
          isUpdate: true,
        };
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, dataForm),
          isUpdate: true,
        };
      }
      profileContext.setModule?.(moduleEdit);

      const {
        pageId,
        pageName,
        type
      } = trackingProps(moduleEdit.type, localizationSelected)

      useAnalyticsSDK
        ? elementCreate({ pageId, pageName, type })
        : sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
          "Module Type": moduleEdit.type,
          "Page ID": localizationSelected?.id || null,
          "Page Name": localizationSelected?.name || "Default",
        });
    },
    [
      module,
      item,
      localizationSelected,
      profileContext.setModule,
      sendSegmentEvent,
    ]
  );

  const onClickDeleteForm = useCallback(() => {
    setVisibleDelete(true);
  }, []);

  const onClickAddForm = useCallback(() => {
    setVisibleEditor(true);
  }, []);

  const handleClickViewData = useCallback(
    (item) => () => {
      if (isContactFormFlagOn) {
        router.push(
          `/admin/data-export?moduleId=${module.id}&formId=${item.id}`
        );
      } else {
        router.push(`/data-export?moduleId=${module.id}&formId=${item.id}`);
      }
    },
    [router]
  );

  return (
    <React.Fragment>
      <div className="module-data-capture-form">
        <ModuleEditor
          module={module}
          dragHandleProps={dragHandleProps}
          confirmDeleteModalProps={{
            className: "module-data-capture-form__delete-modal",
            classNameAction: "m__t--32",
            description: (
              <div>
                <Paragraph preset="regular16">
                  This module will be deleted and you can’t undo this action.
                </Paragraph>
                <Paragraph className="m__t--12" preset="regular16">
                  Don’t worry, your form data won’t be removed and will still be
                  accessible on the Data Capture Form page, under Past Forms.
                </Paragraph>
              </div>
            ),
          }}
        >
          {isEmptyModule(module) ? (
            <React.Fragment>
              <EmptyModule
                titleAction={
                  isContactForm ? "Add New Contact Form" : "Add New Form"
                }
                onClick={onClickAddForm}
              />
            </React.Fragment>
          ) : (
            <DataCaptureFormCard
              item={item}
              title={item.form.name}
              contentSubtitle={item.subTitle}
              contentTitle={item.title}
              image={item.image}
              onDelete={onClickDeleteForm}
              onEdit={onClickAddForm}
              onViewData={item.id ? handleClickViewData(item) : undefined}
              module={module}
            />
          )}
        </ModuleEditor>
        <ConfirmDeleteModal
          className="module-data-capture-form__delete-modal"
          classNameAction="m__t--32"
          show={visibleDelete}
          toggleModal={setVisibleDelete}
          cancelLabel="No Thanks!"
          confirmLabel="Delete"
          title="Are you sure you want to delete this module?"
          description={
            <div>
              <Paragraph preset="regular16">
                This module will be deleted and you can’t undo this action.
              </Paragraph>
              <Paragraph className="m__t--12" preset="regular16">
                Don’t worry, your form data won’t be removed and will still be
                accessible on the Data Capture Form page, under Past Forms.
              </Paragraph>
            </div>
          }
          handleConfirm={onDeleteItem}
        />
        <DataCaptureModal
          show={visibleEditor}
          toggleModal={setVisibleEditor}
          onFinish={onSaveModule}
          item={item}
          isContactForm={isContactForm}
        />
      </div>
    </React.Fragment>
  );
};

export default React.memo(ModuleDataCaptureFrom);
