import React, { useCallback, useState, useRef } from 'react';
import { FlatList, View, Dimensions } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import { usePostGetCountriesRankingMemoriam } from '@api/ranking';

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

import { Profile } from '../Components/Profile';
import { FilterButton, FilterModal } from '../Components/FilterModal';

import { applyModalSort, dataRanking } from '../utils';
import { RankingDropdown, FilterModalRef } from '../utils/types';

import type { Ranking } from '..';

const InMemoriamScreen = () => {
  const [memoriamRanking, setMemoriamRanking] = useState<Ranking[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [filteredData, setFilteredData] = useState<Ranking[]>([]);
  const filterRef = useRef<FilterModalRef>(null);
  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();

  const { data: inMemoriamCountries } = usePostGetCountriesRankingMemoriam();

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

      fetchRanking();
    }, [])
  );

  if (isLoading) return <Loading />;

  return (
    <PageWrapper>
      <Header
        label="In Memoriam"
        rightElement={<FilterButton onPress={() => filterRef.current?.toggle()} />}
      />

      <View style={{ zIndex: 100 }} pointerEvents="box-none">
        <View
          style={{
            position: 'absolute',
            top: 0,
            left: -Dimensions.get('window').width * 0.05,
            width: Dimensions.get('window').width,
            height: Dimensions.get('window').height,
            overflow: 'hidden'
          }}
          pointerEvents="box-none"
        >
          <FilterModal
            ref={filterRef}
            applyFilter={(filterAge, filterRanking, filterCountry) => {
              setConfirmedValueRanking(filterRanking);
              setFilteredData(
                applyModalSort(
                  memoriamRanking,
                  filterAge,
                  filterRanking ?? dataRanking[0],
                  filterCountry
                )
              );
            }}
            countriesData={inMemoriamCountries ? inMemoriamCountries.data : []}
          />
        </View>
      </View>

      <FlatList
        showsVerticalScrollIndicator={false}
        data={filteredData.length > 0 ? filteredData : memoriamRanking}
        keyExtractor={(item) => item.user_id.toString()}
        renderItem={({ item, index }) => (
          <Profile
            userId={item.user_id}
            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_un,
              item.score_unp,
              item.score_dare,
              item.score_tcc,
              item.score_deep,
              item.score_slow,
              item.score_yes,
              item.score_kye,
              item.score_whs
            ]}
            active_score={
              confirmedValueRanking ? confirmedValueRanking.value - 1 : dataRanking[0].value - 1
            }
            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}
            badge_un_25={item.badge_un_25}
            badge_un_50={item.badge_un_50}
            badge_un_75={item.badge_un_75}
            badge_un_100={item.badge_un_100}
            badge_un_150={item.badge_un_150}
            badge_premium={item.badge_premium}
            auth={item.auth}
          />
        )}
      />
    </PageWrapper>
  );
};

export default InMemoriamScreen;
