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

import { Header, Loading, PageWrapper } from '../../../../components';
import { storage, StoreType } from '../../../../storage';

import { Profile } from '../Components/Profile';

import type { Ranking } from '..';

const LPIRankingScreen = () => {
  const [LPIRanking, setLPIRanking] = useState<Ranking[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useFocusEffect(
    useCallback(() => {
      const fetchRanking = async () => {
        const lpi: string = storage.get('lpiRanking', StoreType.STRING) as string;
        setLPIRanking(JSON.parse(lpi).sort((a: Ranking, b: Ranking) => b.score_nm - a.score_nm));
        setIsLoading(false);
      };

      fetchRanking();
    }, [])
  );

  if (isLoading) return <Loading />;

  return (
    <PageWrapper>
      <FlatList
        data={LPIRanking}
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={<Header label="LPI Ranking" />}
        keyExtractor={(item) => item.user_id.toString()}
        onEndReachedThreshold={0.1}
        renderItem={({ item, index }) => (
          <Profile
            key={index}
            index={index}
            first_name={item.first_name}
            last_name={item.last_name}
            avatar={item.avatar}
            date_of_birth={item.age}
            homebase_flag={item.flag1}
            homebase2_flag={item.flag2}
            score={[
              item.score_nm,
              item.score_dare,
              item.score_un,
              item.score_unp,
              item.score_tcc,
              item.score_yes,
              item.score_slow,
              item.score_whs,
              item.score_kye
            ]}
            tbt_score={item.score_tbt}
            tbt_rank={item.rank_tbt}
            badge_tbt={item.badge_tbt}
            badge_1281={item.badge_1281}
            badge_un={item.badge_un}
            auth={item.auth}
          />
        )}
      />
    </PageWrapper>
  );
};

export default LPIRankingScreen;
