import React, { useEffect, useRef } from "react";
import {
  StyleProp,
  ViewStyle,
  Animated,
  Easing,
  Dimensions,
  StyleSheet,
} 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";

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;
};

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

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

export const PlayerDetails = ({
  entry,
  style,
  configuration,
  isTabletLandscape,
  isAudioPlayer,
  isTablet,
}: Props) => {
  const screenData = useTargetScreenData(entry);
  const insets = useSafeAreaInsets();

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

  // 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]);

  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}
        />
      ) : null}
    </Animated.View>
  );
};
