import React, {memo, useCallback, useRef, useState} from 'react';
import {
  LayoutRectangle,
  ScrollView,
  StyleProp,
  View,
  ViewStyle,
} from 'react-native';
import {NavigationState, SceneRendererProps} from 'react-native-tab-view';
import {Chip} from '@components/_HuGo/Chip';

import {TabItem} from '../../../../interfaces';
import {styles} from './styles';

interface Props extends SceneRendererProps {
  navigationState: NavigationState<TabItem>;
  style?: StyleProp<ViewStyle>;
  contentContainerStyle?: StyleProp<ViewStyle>;
}

function TabChipsHeaderComponent({
  jumpTo,
  navigationState,
  style,
  contentContainerStyle,
}: Props) {
  const scrollViewRef = useRef<ScrollView>(null);
  const [tabDimensions, setTabDimensions] = useState<
    {width: number; x: number}[]
  >([]);
  const activeKey = navigationState.index;

  const onTabLayout = useCallback((layout: LayoutRectangle, index: number) => {
    setTabDimensions(current => {
      const newArray = [...current];
      newArray[index] = {width: layout.width, x: layout.x};
      return newArray;
    });
  }, []);

  const onTabPress = useCallback(
    (key: string, index: number) => () => {
      scrollViewRef.current?.scrollTo({x: tabDimensions[index].x});
      jumpTo(key);
    },
    [jumpTo, tabDimensions],
  );

  const onLayout = useCallback(
    (index: number) => (layout: LayoutRectangle) => onTabLayout(layout, index),
    [onTabLayout],
  );

  return (
    <View style={styles.container}>
      <ScrollView
        ref={scrollViewRef}
        bounces={false}
        showsHorizontalScrollIndicator={false}
        horizontal
        contentContainerStyle={[styles.content, contentContainerStyle]}
        style={style}>
        {navigationState.routes.map((route, index) => (
          <Chip
            key={route.key}
            text={route.label}
            onPress={onTabPress(route.key, index)}
            onLayout={onLayout(index)}
            active={index === activeKey}
            showActiveIcon={false}
          />
        ))}
      </ScrollView>
    </View>
  );
}

export const TabsChipsHeader = memo(TabChipsHeaderComponent);
