import React, { useCallback } from "react";
import { StyleSheet, View } from "react-native";
import { Spinner } from "@applicaster/zapp-react-native-ui-components/Components/Spinner";
import type { Subject } from "rxjs";
import { useStateFromSubscribe } from "@applicaster/zapp-react-native-utils/reactHooks/state/useStateFromSubscribe";

type LoadingState = {
  waitForAllComponents: boolean;
  index: number;
  done: boolean;
};

type State = {
  visible: boolean;
  isAnyLoaded: boolean;
};

type Props = {
  flatListHeight?: number;
  loadingState: Subject<LoadingState>;
};

const FOOTER_COMPONENT_HEIGHT = 200;

const footerStyles = StyleSheet.create({
  container: {
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
});

function RiverFooterComponent(props: Props) {
  const { flatListHeight, loadingState } = props;

  const { visible, isAnyLoaded } = useStateFromSubscribe<LoadingState, State>(
    loadingState,
    useCallback(
      ({ index, done, waitForAllComponents }, setState) =>
        setState(() => ({
          visible: !done,
          isAnyLoaded: index >= 0 || waitForAllComponents,
        })),
      []
    ),
    {
      visible: true,
      isAnyLoaded: false,
    }
  );

  if (!visible) return null;

  return (
    <View
      renderToHardwareTextureAndroid
      style={[
        footerStyles.container,
        {
          height: isAnyLoaded ? FOOTER_COMPONENT_HEIGHT : flatListHeight,
        },
      ]}
    >
      <Spinner size={isAnyLoaded ? "small" : "large"} />
    </View>
  );
}

export const RiverFooter = React.memo<Props>(RiverFooterComponent);
