import React, { useState } from 'react';
import {
  View,
  I18nManager,
  SafeAreaView,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import TTypography from '../TTypography/TTypography';
import { TypographyVariant } from '../TTypography/TTypographyEnum';
import PagerView from 'react-native-pager-view';
import { withTheme, useTheme } from '../../core/theming';
import type { Theme } from '../../utils/types';
import { styles } from './TTopBar.style';

interface Props {
  screens: ScreenData[];
  initialPage?: number;
  tabStyle?: object;
  tabHighlightColor?: string;
  tabTextColor?: string;
  containerHeight?: any;
  containerWidth?: any;
  theme: Theme;
}
interface ScreenData {
  name: string;
  component: any;
}

const MyPager = ({
  screens,
  initialPage,
  tabStyle,
  tabHighlightColor,
  tabTextColor,
  containerHeight,
}: Props): any => {
  const pagerRef = React.useRef<PagerView>(null);
  const [selectedPage, setPage] = useState(initialPage || 0);

  const { colors } = useTheme();
  const stylesWithProp = styles({ colors, tabHighlightColor, containerHeight });

  const renderItem = (item: any, index: number) => {
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => {
          pagerRef.current?.setPage(index);
        }}
        style={
          index === selectedPage
            ? { ...stylesWithProp.tabContainerSelected, ...tabStyle }
            : { ...stylesWithProp.tabContainer, ...tabStyle }
        }
      >
        <TTypography
          variant={TypographyVariant.PRIMARY_BOLD}
          color={tabTextColor}
        >
          {item.name}
        </TTypography>
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView>
      <View style={stylesWithProp.flatListContainer}>
        <FlatList
          data={screens}
          horizontal
          showsHorizontalScrollIndicator={false}
          renderItem={({ item, index }) => renderItem(item, index)}
          keyExtractor={(item) => item.name}
        />
      </View>
      <PagerView
        ref={pagerRef}
        style={stylesWithProp.pagerView}
        initialPage={selectedPage}
        layoutDirection={I18nManager.isRTL ? 'rtl' : 'ltr'}
        onPageScroll={(event) => {
          setPage(event.nativeEvent.position);
        }}
      >
        {screens.map((screen, index) => {
          return <View key={index + 1}>{screen.component()}</View>;
        })}
      </PagerView>
    </SafeAreaView>
  );
};

export default withTheme(MyPager);
