import { useEffect } from "react";
import {
  BackHandler,
  Image,
  StyleSheet,
  TouchableOpacity,
  View,
  ViewStyle,
} from "react-native";
import { GenericActionPayload } from "../../App/common/actions/GenericAction";
import { CtaData } from "../../App/common/interface";
import { HeaderWithAssetsWidgetData } from "../../App/common/interface/widgets/widgetData/HeaderWithAssetsWidgetData";
import { StyledImage } from "../StyledImage";
import { StyledLottie } from "./styled-lottie/StyledLottie";
import { StyledText } from "./styled-text/StyledText";

const HeaderWithAssetsWidget = ({
  widgetData,
  widgetStyle,
  handleActions,
  widgetIndex,
  handleClick,
}: {
  widgetData: HeaderWithAssetsWidgetData;
  widgetStyle: ViewStyle;
  handleActions: (
    value?: any | undefined | null,
    screenActionPayload?: GenericActionPayload,
  ) => void;
  widgetIndex: number;
  handleClick?: (ctaData: CtaData) => void;
}) => {
  const handleBackButtonClick = () => {
    handleActions(null, widgetData?.action);
    handleClick &&
      widgetData?.leftIcon?.cta &&
      handleClick(widgetData?.leftIcon?.cta);
    return true;
  };

  useEffect(() => {
    BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
    return () => {
      BackHandler.removeEventListener(
        "hardwareBackPress",
        handleBackButtonClick,
      );
    };
  }, [widgetData]);

  return (
    <View style={[styles.container, widgetStyle]}>
      {widgetData.leftIcon && (
        <TouchableOpacity onPress={() => handleBackButtonClick()}>
          <Image
            source={{ uri: widgetData.leftIcon?.url }}
            style={widgetData.leftIcon?.imageStyle}
          />
        </TouchableOpacity>
      )}
      {widgetData.leftLottie && (
        <StyledLottie
          lottieFieldData={widgetData?.leftLottie}
          handleClick={handleClick}
        />
      )}
      {widgetData.centerTitle && (
        <StyledText textFieldData={widgetData?.centerTitle} />
      )}
      {widgetData.rightIcon &&
        (widgetData.isRightAssetVisible === false ? false : true) && (
          <View>
            <StyledImage
              imageFieldData={widgetData?.rightIcon}
              handleClick={handleClick}
            />
          </View>
        )}
      {widgetData.rightLottie &&
        (widgetData.isRightAssetVisible === false ? false : true) && (
          <StyledLottie
            lottieFieldData={widgetData?.rightLottie}
            handleClick={handleClick}
          />
        )}
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    width: "100%",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 16,
  },
});
export default HeaderWithAssetsWidget;
