import React, { useEffect, useRef } from "react";
import {
  Animated,
  Dimensions,
  Easing,
  StyleProp,
  StyleSheet,
  ViewStyle,
} from "react-native";
import { useTargetScreenData } from "@applicaster/zapp-react-native-utils/reactHooks/screen";
import { ComponentsMap } from "@applicaster/zapp-react-native-ui-components/Components/River/ComponentsMap";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { isNilOrEmpty } from "@applicaster/zapp-react-native-utils/reactUtils/helpers";
import { useIsTablet } from "@applicaster/zapp-react-native-utils/reactHooks";
import { useDelayedPlayerDetails } from "./hooks";

const { width: SCREEN_WIDTH } = Dimensions.get("screen");

type Configuration = {
  [key: string]: any;
  modal_background_color?: string;
};

type Props = {
  entry: ZappEntry;
  style: StyleProp<ViewStyle>;
  configuration: Configuration;
  isTabletLandscape?: boolean;
  isAudioPlayer?: boolean;
  isTablet?: boolean;
  inline?: any;
  docked?: boolean;
  isModal?: boolean;
  pip?: boolean;
};

const containerStyle = ({
  modal_background_color,
}: Configuration): ViewStyle => ({
  backgroundColor: modal_background_color,
});

// const audioMarginStyle = { marginTop: 0, marginBottom: 0 };

export const PlayerDetails = ({
  entry,
  style,
  configuration,
  isTabletLandscape = false,
  isAudioPlayer,
  inline,
  docked,
  isModal,
  pip,
}: Props) => {
  const isInlineModal = inline && isModal;

  // Mounting the PlayerDetails component is a resource-intensive process.
  // Therefore, for performance reasons, we mount it with a delay to make the rotation process as smooth as possible.
  // The flow is as follows: the rotation occurs first, and then, after a short delay, we mount the PlayerDetails component.
  // This helps to avoid blocking the rotation and any animations related to the rotation.
  const isShowPlayerDetails = useDelayedPlayerDetails({
    isInline: isInlineModal,
    isDocked: docked,
    isPip: pip,
  });

  const isTablet = useIsTablet();
  const screenData = useTargetScreenData(entry);
  const insets = useSafeAreaInsets();

  const extraTabletStyles =
    !isAudioPlayer && isTabletLandscape
      ? { marginTop: -insets.top, paddingTop: insets.top + 20 }
      : null;

  // Animation setup
  const translateY = useRef(new Animated.Value(50)).current;
  const opacity = useRef(new Animated.Value(0)).current;

  const runAnimation = () => {
    Animated.timing(translateY, {
      toValue: -30,
      duration: 500,
      easing: Easing.inOut(Easing.ease),
      useNativeDriver: true,
    }).start();

    Animated.timing(opacity, {
      toValue: 1,
      duration: 500,
      easing: Easing.inOut(Easing.ease),
      useNativeDriver: true,
    }).start();
  };

  useEffect(() => {
    if (isAudioPlayer) {
      setTimeout(() => runAnimation(), 1500);
    }
  }, [isAudioPlayer]);

  if (isNilOrEmpty(screenData?.ui_components) || !isShowPlayerDetails) {
    return null;
  }

  return (
    <Animated.View
      style={[
        style,
        extraTabletStyles,
        containerStyle(configuration),
        isAudioPlayer && {
          transform: [{ translateY }],
          opacity,
        },
        {
          // workaround for avoid wrong text-height after going back to portrait rotation
          // we don't see this view in landscape mode, so we are able to use fixed width from portrait mode
          width: isTablet
            ? undefined
            : (StyleSheet.flatten(style)?.width ?? SCREEN_WIDTH),
        },
      ]}
    >
      {screenData ? (
        <ComponentsMap
          riverId={screenData.id}
          feed={screenData?.data?.source}
          riverComponents={screenData.ui_components}
          isScreenWrappedInContainer
        />
      ) : null}
    </Animated.View>
  );
};
