import React from "react";
import { View } from "react-native";
import { GenericActionPayload } from "../../App/common/actions/GenericAction";
import { CtaData } from "../../App/common/interface";
import { Widget } from "../../App/common/interface/widgets/Widget";
import WidgetActionHandler from "../../App/common/widgets/widget-actions/WidgetActionHandler";
import { WidgetActionTypes } from "../../App/common/widgets/widget-actions/WidgetActionTypes";
import { GetWidgetView } from "../../App/common/widgets/widgetResolver";
import { ScreenState } from "../../App/common/screen/BaseScreen";

const BaseWidget = ({
  widget,
  handleScreenActions,
  screenState,
  handleClick,
  widgetIndex,
}: {
  widget: Widget;
  handleScreenActions: (actionPayload?: GenericActionPayload) => void;
  screenState?: ScreenState | null;
  handleClick?: (ctaData: CtaData) => void;
  widgetIndex: number;
}) => {
  function handleWidgetActions(
    value: any | undefined | null,
    actionPayloadList: GenericActionPayload | undefined
  ) {
    let payload = actionPayloadList;
    let needPayloadCompression = false;
    actionPayloadList?.metaData?.forEach((actionPayload) => {
      if (actionPayload?.actionType === WidgetActionTypes.UPDATE_WIDGET_DATA) {
        needPayloadCompression = true;
        return;
      }
    });
    if (!!value && needPayloadCompression) {
      payload = WidgetActionHandler.getTargetWidgetActionPayload(
        value,
        actionPayloadList
      );
    }
    handleScreenActions(payload);
  }
  widget = {
    ...widget,
    widgetVisibility:
      widget.widgetVisibility !== undefined ? widget.widgetVisibility : true,
  };
  return widget.widgetVisibility ? (
    <View style={widget.widgetStyle}>
      {GetWidgetView.getWidget(
        widget,
        handleWidgetActions,
        widgetIndex,
        handleClick,
        screenState
      )}
    </View>
  ) : (
    <></>
  );
};

export default BaseWidget;
