/* eslint-enable react-native/no-unused-styles */
import React, { useMemo } from "react";
import { View, StyleSheet } from "react-native";
import { FocusableGroup } from "@applicaster/zapp-react-native-ui-components/Components/FocusableGroup";
import { platformSelect } from "@applicaster/zapp-react-native-utils/reactUtils";
import { useNavigation } from "@applicaster/zapp-react-native-utils/reactHooks/navigation";
import { withNestedNavigationContextProvider } from "@applicaster/zapp-react-native-ui-components/Contexts/NestedNavigationContext";

const getStyles = () => {
  return StyleSheet.create({
    tabContent: platformSelect({
      tvos: {
        flex: 1,
        zIndex: -1,
        marginLeft: 1,
        paddingLeft: 1,
      },
    }),
    tabContentFocusableGroup: platformSelect({
      tvos: {
        width: "100%",
        height: "100%",
        // hack to limit the size of the screen container for tvos, so it doesn't intercept the focus from tabs when navigating down
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: "transparent",
      },
    }),
  });
};

const FocusableWrapper = ({ groupId, id, parentFocus, children }) => {
  const { tabContent, tabContentFocusableGroup } = useMemo(
    () => getStyles(),
    []
  );

  return platformSelect({
    android_tv: <>{children}</>,
    default: (
      <View style={tabContent}>
        <FocusableGroup
          groupId={groupId}
          id={id}
          preferredFocus={false}
          shouldUsePreferredFocus
          style={tabContentFocusableGroup}
          nextFocusUp={parentFocus?.nextFocusUp}
        >
          {children}
        </FocusableGroup>
      </View>
    ),
  });
};

const TabContentComponent = ({
  Component,
  groupId,
  id,
  entry,
  parentFocus,
}: TabContentProps) => {
  const navigator = useNavigation();
  const nestedEntry = navigator.getNestedEntry();
  const isContextUptoDate = nestedEntry?.id === entry?.id;

  return isContextUptoDate && Component ? (
    <FocusableWrapper groupId={groupId} id={id} parentFocus={parentFocus}>
      <Component />
    </FocusableWrapper>
  ) : null;
};

export const TabContent =
  withNestedNavigationContextProvider(TabContentComponent);
