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

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

import { Header, Loading, PageWrapper } from '../../../../components';
import { getStatistic, StatisticType } from '../../../../database/statisticsService';

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

type Props = {
  route: { params: { title: string; url1: string; url2: string | null } };
};

//TODO: For future fix types

const StatisticsListScreen: FC<Props> = ({ route }) => {
  const title = route.params.title;
  const url1 = route.params.url1;
  const url2 = route.params.url2;

  const [isLoading, setIsLoading] = useState(true);
  const [statistic, setStatistic] = useState<StatisticType | null>(null);

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

        if (!data) return;

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

      fetchStatistic();
    }, [url1])
  );

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

  return (
    <PageWrapper>
      <Header label={title} />
      {statistic.comment && <Text style={ItemStyles.comment}>{statistic.comment}</Text>}
      <FlatList
        contentContainerStyle={{ gap: 10 }}
        horizontal={false}
        data={statistic.ranking}
        renderItem={({ item, index }) => (
          <RenderItem item={item} index={index} ranking={statistic?.ranking} />
        )}
        showsVerticalScrollIndicator={false}
      />
    </PageWrapper>
  );
};

export default StatisticsListScreen;
