import React, { useCallback, useEffect, useState } from 'react';
import { FlatList, Text } from 'react-native';
import { useFocusEffect, useNavigation } from '@react-navigation/native';

import { RenderItem } from '../Components/StatisticRouter';

import { Header, Loading, PageWrapper } from '../../../../components';
import { getStatistic, StatisticType } from '../../../../database/statisticsService';
import { isType1, isType5, isType7 } from '../StatisticsListScreen/funcs';

import { ItemStyles } from '../Components/styles';

const StatisticsListScreen = ({ route }: { route: any }) => {
  const title = route.params.title;
  const url1 = route.params.url1;
  const url2 = route.params.url2;
  const navigation = useNavigation();

  const [isLoading, setIsLoading] = useState(true);
  const [statistic, setStatistic] = useState<StatisticType | null>(null);
  const [blockIndexes, setBlockIndexes] = useState<{ [key: number]: number }>({});

  useFocusEffect(
    useCallback(() => {
      if (!statistic) return;
      setIsLoading(false);
    }, [statistic])
  );

  useEffect(() => {
    function fetchStatistic() {
      const data = getStatistic(url1, url2);

      if (!data) return;

      setStatistic(JSON.parse(data as unknown as string) as unknown as StatisticType);
    }

    fetchStatistic();
  }, [url1]);

  const calculateBlockIndexes = (ranking: any) => {
    let indexes: { [key: number]: number } = {};
    let currentBlockIdentifier = '';
    let indexInBlock = isType1(ranking[0]) || isType5(ranking[0]) || isType7(ranking[0]) ? -1 : 0;

    ranking.forEach((item: any, index: number) => {
      const blockIdentifier = item.megaregion || item.mega_name || item.series_name || item.country;

      if (isType1(item) || isType5(item) || isType7(item)) {
        indexInBlock++;
      } else if (blockIdentifier !== currentBlockIdentifier) {
        currentBlockIdentifier = blockIdentifier;
        indexInBlock = 0;
      } else {
        indexInBlock++;
      }

      indexes[index] = indexInBlock;
    });

    return indexes;
  };

  useEffect(() => {
    if (statistic?.ranking) {
      setBlockIndexes(calculateBlockIndexes(statistic.ranking));
    }
  }, [statistic]);

  if (isLoading) return <Loading />;
  if (!statistic) return null;

  return (
    <PageWrapper style={{ flex: 1 }}>
      <Header label={title} />
      {statistic.ranking ? (
        <FlatList
          contentContainerStyle={{ gap: 12, paddingBottom: 16 }}
          style={{ flex: 1 }}
          horizontal={false}
          data={statistic.ranking as any}
          keyExtractor={(item, index) => index.toString()}
          initialNumToRender={20}
          renderItem={({ item, index }) => {
            const blockIndex: number = blockIndexes[index];
            return (
              <RenderItem
                item={item}
                blockIndex={blockIndex}
                idx={index}
                ranking={statistic?.ranking}
                navigation={navigation}
              />
            );
          }}
          showsVerticalScrollIndicator={false}
          ListHeaderComponent={
            statistic.comment ? (
              <Text style={ItemStyles.comment}>{statistic.comment.replaceAll('<br/>', '\n')}</Text>
            ) : null
          }
        />
      ) : null}
    </PageWrapper>
  );
};

export default StatisticsListScreen;
