import React, { useEffect, useState } from 'react';
import { View, Text, Pressable } from 'react-native';
import { Tabs, MaterialTabBar, MaterialTabItemProps } from 'react-native-collapsible-tab-view';
import { Colors } from 'src/theme';

interface RouteType {
  key: string;
  title: string;
}

interface TabViewWrapperProps {
  routes: RouteType[];
  renderScene: ({ route }: { route: RouteType }) => React.ReactNode;
  setIndex: (index: number) => void;
  selectedIndex: number;
  lazy?: boolean;
  renderBadge?: (props: { route: RouteType }) => React.ReactNode;
}

const CustomTabItem = ({
  name,
  label,
  onLayout,
  onPress,
  style,
  index,
  renderBadge,
  selectedIndex,
  route
}: MaterialTabItemProps<any> & {
  renderBadge?: (props: { route: RouteType }) => React.ReactNode;
  selectedIndex: number;
  route: RouteType;
}) => {
  const isFocused = index === selectedIndex;

  return (
    <Pressable
      onPress={() => onPress(name)}
      onLayout={onLayout}
      style={() => [
        style,
        {
          opacity: isFocused ? 1 : 0.4,
          alignItems: 'center',
          justifyContent: 'center',
          flex: 1,
          position: 'relative'
        }
      ]}
    >
      <Text
        style={{
          color: Colors.DARK_BLUE,
          textAlign: 'center',
          fontSize: 14,
          fontWeight: '600',
          paddingHorizontal: 4
        }}
        numberOfLines={2}
        adjustsFontSizeToFit
        minimumFontScale={0.8}
      >
        {typeof label === 'string' ? label : ''}
      </Text>

      {renderBadge && (
        <View style={{ position: 'absolute', top: 4, right: 10 }}>{renderBadge({ route })}</View>
      )}
    </Pressable>
  );
};

const TabViewWrapper: React.FC<TabViewWrapperProps> = ({
  routes,
  renderScene,
  setIndex,
  selectedIndex,
  lazy = false,
  renderBadge
}) => {
  const [hasMounted, setHasMounted] = useState(false);

  useEffect(() => {
    if (!hasMounted) setHasMounted(true);
  }, []);

  return (
    <Tabs.Container
      initialTabName={!hasMounted ? routes[selectedIndex].key : undefined}
      headerHeight={0}
      containerStyle={{ flex: 1 }}
      headerContainerStyle={{
        elevation: 0,
        shadowOpacity: 0,
        borderBottomWidth: 0
      }}
      tabBarHeight={48}
      onIndexChange={setIndex}
      lazy={lazy}
      renderTabBar={(props) => (
        <MaterialTabBar
          {...props}
          TabItemComponent={(tabItemProps) => (
            <CustomTabItem
              {...tabItemProps}
              renderBadge={renderBadge}
              selectedIndex={selectedIndex}
              route={routes[tabItemProps.index]}
            />
          )}
          style={{
            backgroundColor: '#fff',
            elevation: 0,
            shadowOpacity: 0,
            borderBottomWidth: 0
          }}
          tabStyle={{
            minHeight: 48,
            justifyContent: 'center'
          }}
          indicatorStyle={{
            backgroundColor: Colors.DARK_BLUE,
            height: 2
          }}
        />
      )}
    >
      {routes.map((route) => (
        <Tabs.Tab key={route.key} name={route.key} label={route.title}>
          <View
            style={{
              flex: 1,
              width: '100%',
              paddingTop: 48,
              paddingHorizontal: '4%'
            }}
          >
            {renderScene({ route })}
          </View>
        </Tabs.Tab>
      ))}
    </Tabs.Container>
  );
};

export default TabViewWrapper;
