import React, { useEffect, useRef, useState } from "react";
import { Platform, View, findNodeHandle } from "react-native";
import Modal from "react-native-modal";
import { GenericActionPayload } from "../../App/common/actions/GenericAction";
import {
  AnalyticsEventNameConstants,
  AnalyticsMethodNameConstant,
  BOTTOMSHEET_ANIMATION_DURATION,
  NAVIGATION_ERROR,
  OsTypeConstants,
  TimeoutConstants,
} from "../../App/common/constants";
import { sendAsAnalyticsEvent } from "../../App/common/hooks/useAnalyticsEvent";
import { CtaData, CtaType } from "../../App/common/interface";
import { ModalView } from "../../App/common/interface/modals/ModalView";
import { GetModalView } from "../../App/common/modals/modalViewResolver";
import { NativeDeeplinkNavigatorModule } from "../../App/common/native-module/NativeModules";
import styles from "../../App/common/styles/BaseBottomSheetComponentStyles";
import WidgetActionHandler from "../../App/common/widgets/widget-actions/WidgetActionHandler";
import { WidgetActionTypes } from "../../App/common/widgets/widget-actions/WidgetActionTypes";

const BaseBottomSheetComponent = ({
  onBottomSheetAnimationEnd,
  showModal,
  onClose,
  modalView,
  handleActions,
}: {
  onBottomSheetAnimationEnd?: (id: number | null) => void;
  showModal: boolean;
  onClose: () => void;
  modalView: ModalView | undefined;
  handleActions: (actionPayload?: GenericActionPayload) => void;
}) => {
  const [isModalVisible, setModalVisible] = useState(showModal);
  const modalRef = useRef(null);

  const closeModal = () => {
    setModalVisible(false);
    setTimeout(() => {
      onClose();
    }, BOTTOMSHEET_ANIMATION_DURATION);
  };

  const handleModalClick = (cta: CtaData) => {
    switch (cta?.type) {
      case CtaType.DISMISS_MODAL:
        if (!!cta?.analyticsEventProperties) {
          sendAsAnalyticsEvent(cta?.analyticsEventProperties);
        }
        closeModal();
        break;
      default:
        if (Platform.OS === OsTypeConstants.IOS) {
          closeModal();
        }
        setTimeout(
          () => {
            try {
              NativeDeeplinkNavigatorModule.navigateToNaviDeeplinkNavigator(
                JSON.stringify(cta),
              );
            } catch (error) {
              sendAsAnalyticsEvent({
                name: AnalyticsEventNameConstants.HI_INVALID_SCREEN_CTA,
                properties: {
                  methodName:
                    AnalyticsMethodNameConstant.HANDLE_CTA_CLICK_BOTTOMSHEET,
                  reason: error?.toString() || NAVIGATION_ERROR,
                },
              });
            }
          },
          Platform.OS === OsTypeConstants.IOS
            ? TimeoutConstants.TIMEOUT_1000
            : 0,
        );
    }
  };

  function handleModalActions(
    value: any | undefined | null,
    actionPayloadList: GenericActionPayload | undefined,
  ) {
    let payload = actionPayloadList;
    const needPayloadCompression = actionPayloadList?.metaData?.some(
      actionPayload =>
        actionPayload?.actionType === WidgetActionTypes.UPDATE_WIDGET_DATA,
    );

    if (value && needPayloadCompression) {
      payload = WidgetActionHandler.getTargetWidgetActionPayload(
        value,
        actionPayloadList,
      );
    }
    handleActions(payload);
  }

  useEffect(() => {
    setModalVisible(showModal);
    if (typeof onBottomSheetAnimationEnd === "function") {
      const nodeId = findNodeHandle(modalRef?.current);
      onBottomSheetAnimationEnd(nodeId);
    }
  }, [showModal]);

  return (
    <Modal
      onBackdropPress={() => {
        closeModal();
      }}
      onBackButtonPress={() => {
        closeModal();
      }}
      hasBackdrop={true}
      backdropOpacity={0.65}
      isVisible={isModalVisible}
      swipeDirection="down"
      onSwipeComplete={() => closeModal()}
      onModalHide={() => onClose()}
      animationIn="slideInUp"
      animationOut="slideOutDown"
      animationInTiming={BOTTOMSHEET_ANIMATION_DURATION}
      animationOutTiming={BOTTOMSHEET_ANIMATION_DURATION}
      useNativeDriverForBackdrop={true}
      hideModalContentWhileAnimating={true}
      style={styles.modal}
    >
      <View ref={modalRef} style={[styles.modalContent, modalView?.modalStyle]}>
        {/* <View style={styles.barContainer}>
          <Text style={styles.barIcon} />
        </View> */}
        {GetModalView.getModal(
          modalView!!,
          handleModalClick,
          handleModalActions,
        )}
      </View>
    </Modal>
  );
};

export default BaseBottomSheetComponent;
