import React, { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { FlashList } from '@shopify/flash-list';

import {
  Header,
  HorizontalTabView,
  Loading,
  PageWrapper,
  WarningModal
} from '../../../../components';
import SeriesRankingItem from '../Components/SeriesRankingItem';

import { useGetSeriesRanking } from '@api/series';
import { useConnection } from 'src/contexts/ConnectionContext';
import { NAVIGATION_PAGES } from 'src/types';
import { StoreType, storage } from 'src/storage';
import { Colors } from 'src/theme';
import { SeriesRanking } from '../utils/types';
import { SafeAreaView } from 'react-native-safe-area-context';

const SeriesRankingListScreen = ({ route }: { route: any }) => {
  const name = route.params?.name;
  const id = route.params?.id;
  const series = route.params?.series;
  const [index, setIndex] = useState(0);
  const [routes, setRoutes] = useState<{ key: string; title: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalType, setModalType] = useState<string | null>(null);

  useEffect(() => {
    if (series) {
      const parsedRoutes = series.map((item: { id: string; name: string }) => ({
        key: item.id,
        title: item.name
      }));

      setRoutes([{ key: id, title: '  All  ' }, ...(parsedRoutes || [])]);
    }
    setLoading(false);
  }, [series]);

  if (loading) return <Loading />;

  return (
    <SafeAreaView style={{ height: '100%', flex: 1 }} edges={['top']}>
      <View style={{ marginLeft: '5%', marginRight: '5%' }}>
        <Header label={name} />
      </View>
      {series ? (
        <HorizontalTabView
          index={index}
          setIndex={setIndex}
          routes={routes}
          maxTabHeight={50}
          renderScene={({ route }: { route: { key: string; title: string } }) => (
            <SeriesList groupId={+route.key} setModalType={setModalType} />
          )}
          lazy={true}
        />
      ) : (
        <View
          style={{
            marginLeft: '5%',
            marginRight: '5%',
            flex: 1
          }}
        >
          <SeriesList groupId={id} setModalType={setModalType} />
        </View>
      )}
      {modalType && (
        <WarningModal type={modalType} isVisible={true} onClose={() => setModalType(null)} />
      )}
    </SafeAreaView>
  );
};

const SeriesList = React.memo(
  ({
    groupId,
    setModalType
  }: {
    groupId: number;
    setModalType: Dispatch<SetStateAction<string | null>>;
  }) => {
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(0);
    const { data } = useGetSeriesRanking(groupId, page, 50, true);
    const [allData, setAllData] = useState<SeriesRanking[]>([]);
    const netInfo = useConnection();
    const navigation = useNavigation();
    const token = storage.get('token', StoreType.STRING);
    const [isLoadingMore, setIsLoadingMore] = useState(false);

    useEffect(() => {
      if (data && data.result == 'OK') {
        setAllData((prevData) => [...prevData, ...data.data.ranking]);
        setLoading(false);
        setIsLoadingMore(false);
      }
    }, [data]);

    const handlePress = useCallback(
      (userId: number) => {
        if (!netInfo?.isInternetReachable) {
          setModalType('offline');
        } else if (!token) {
          setModalType('unauthorized');
        } else {
          navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
        }
      },
      [netInfo, token, navigation, data]
    );

    const handleEndReached = useCallback(() => {
      if (
        data &&
        data.result === 'OK' &&
        page < data.data.max_pages &&
        !isLoadingMore &&
        netInfo?.isInternetReachable
      ) {
        setIsLoadingMore(true);
        setPage((prevPage) => prevPage + 1);
      }
    }, [data, page, isLoadingMore, netInfo?.isInternetReachable]);

    const ListFooter = ({ isLoading }: { isLoading: boolean }) =>
      isLoading ? <ActivityIndicator size="large" color={Colors.DARK_BLUE} /> : null;

    if (loading) return <Loading />;

    return (
      <FlashList
        viewabilityConfig={{
          waitForInteraction: true,
          itemVisiblePercentThreshold: 50,
          minimumViewTime: 1000
        }}
        contentContainerStyle={{ paddingVertical: 16 }}
        data={allData}
        showsVerticalScrollIndicator={false}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }: { item: SeriesRanking; index: number }) => (
          <SeriesRankingItem item={item} index={index} onPress={handlePress} />
        )}
        onEndReached={handleEndReached}
        onEndReachedThreshold={0.1}
        ListFooterComponent={<ListFooter isLoading={isLoadingMore} />}
      />
    );
  }
);

export default SeriesRankingListScreen;
