import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import { StoreType, storage } from 'src/storage';
import { fetchFullRanking } from '@api/ranking';

export interface Ranking {
  user_id: number,
  score_dare: number,
  score_nm: number,
  score_un: number,
  score_unp: number,
  score_tcc: number,
  score_deep: number,
  score_whs: number,
  score_kye: number,
  score_tbt: number,
  score_yes: number,
  score_slow: number,
  rank_tbt: number,
  avatar: string,
  first_name: string,
  last_name: string,
  age: number,
  flag1: string,
  flag2: string,
  badge_1281: number,
  badge_un: number,
  badge_supreme: number,
  badge_tbt: number,
  badge_offline: number,
  patreon: number,
  country: string,
  auth: number,
  rank: number,
  country_rank: number,
  dod: number,
  ukr: number,
  badges: number,
  arrow_nm: number,
  arrow_un: number,
  arrow_unp: number,
  arrow_dare: number,
  arrow_yes: number,
  arrow_whs: number,
  arrow_tcc: number,
  arrow_tbt: number,
  arrow_slow: number,
  arrow_kye: number,
}

const RankingScreen = () => {
  const [masterRanking, setMasterRanking] = useState<Ranking[]>([]);
  const { mutateAsync } = fetchFullRanking();

  const ranking: string = storage.get('masterRanking', StoreType.STRING) as string;
  const lpi: string = storage.get('lpiRanking', StoreType.STRING) as string;
  const inHistory: string = storage.get('inHistoryRanking', StoreType.STRING) as string;

  useEffect(() => {
    setMasterRanking(
      JSON.parse(ranking).sort((a: Ranking, b: Ranking) => b.score_nm - a.score_nm)
    );
  }, [ranking]);

  const getFullRanking = async () => {
    await mutateAsync(undefined, {
      onSuccess: (data) => {
        setMasterRanking(data.data);
      }
    });
  }

  return (
    <FlatList
      data={masterRanking}
      keyExtractor={(item) => item.user_id.toString()}
      renderItem={({ item }) => (
        <View style={{ display: 'flex', flexDirection: 'row' }}>
          <Text>{item.score_nm}</Text>
          <Text>{item.last_name}</Text>
        </View>
      )}
      onEndReached={() => getFullRanking()}
      onEndReachedThreshold={0.1}
    />
  );
};

export default RankingScreen;
