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

import { useGetFullRanking, usePostGetCountriesRanking } from '@api/ranking';

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

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

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

import type { Ranking } from '..';
import { useConnection } from 'src/contexts/ConnectionContext';
import { updateMasterRanking } from 'src/database';

const MasterRankingScreen = () => {
  const { data: fullData } = useGetFullRanking();
  const { data: masterCountries } = usePostGetCountriesRanking();
  const netInfo = useConnection();

  const [masterRanking, setMasterRanking] = useState<Ranking[]>([]);
  const [fullRanking, setFullRanking] = useState<Ranking[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [filteredData, setFilteredData] = useState<Ranking[]>([]);
  const [isModalVisible, setModalVisible] = useState(false);
  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();

  useFocusEffect(
    useCallback(() => {
      const fetchRanking = async () => {
        const ranking = storage.get('masterRanking', StoreType.STRING) as string;
        let indexCounter = 0;
        if (!ranking) {
          updateMasterRanking();
          setMasterRanking(
            fullData
              ? fullData?.data
                  ?.sort(
                    (a: Omit<Ranking, 'displayIndex'>, b: Omit<Ranking, 'displayIndex'>) =>
                      b.score_nm - a.score_nm || b.score_un - a.score_un || a.age - b.age
                  )
                  .map((item) => {
                    return item.dod !== 1
                      ? { ...item, displayIndex: indexCounter++ }
                      : { ...item, displayIndex: -1 };
                  })
              : []
          );

          return;
        }

        setMasterRanking(
          JSON.parse(ranking)
            .sort(
              (a: Ranking, b: Ranking) =>
                b.score_nm - a.score_nm || b.score_un - a.score_un || a.age - b.age
            )
            .map((item: Ranking) => {
              return item.dod !== 1
                ? { ...item, displayIndex: indexCounter++ }
                : { ...item, displayIndex: -1 };
            })
        );
        setIsLoading(false);
      };

      fetchRanking();
    }, [])
  );

  useEffect(() => {
    if (fullData) {
      let indexCounter = 0;
      setFullRanking(
        fullData?.data
          ?.sort(
            (a: Omit<Ranking, 'displayIndex'>, b: Omit<Ranking, 'displayIndex'>) =>
              b.score_nm - a.score_nm || b.score_un - a.score_un || a.age - b.age
          )
          .map((item) => {
            return item.dod !== 1
              ? { ...item, displayIndex: indexCounter++ }
              : { ...item, displayIndex: -1 };
          })
      );
    }
  }, [fullData]);

  if (isLoading) return <Loading />;

  const getFullRanking = async () => {
    if (netInfo?.isInternetReachable && fullRanking) {
      setMasterRanking(fullRanking);
    }
  };

  return (
    <PageWrapper>
      <FilterModal
        isModalVisible={isModalVisible}
        setModalVisible={(value) => setModalVisible(value)}
        applyFilter={(filterAge, filterRanking, filterCountry) => {
          setConfirmedValueRanking(filterRanking);
          setFilteredData(
            applyModalSort(
              netInfo?.isInternetReachable && fullRanking ? fullRanking : masterRanking,
              filterAge,
              filterRanking ?? dataRanking[0],
              filterCountry
            )
          );
          setModalVisible(false);
        }}
        countriesData={masterCountries ? masterCountries.data : []}
      />

      <Header
        label="Master Ranking"
        rightElement={<FilterButton onPress={() => setModalVisible(!isModalVisible)} />}
      />

      <FlatList
        showsVerticalScrollIndicator={false}
        data={filteredData.length != 0 ? filteredData : masterRanking}
        keyExtractor={(item) => item.user_id.toString()}
        renderItem={({ item, index }) => (
          <Profile
            userId={item.user_id}
            key={index}
            index={item.displayIndex}
            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}
            auth={item.auth}
          />
        )}
        onEndReached={() => getFullRanking()}
        onEndReachedThreshold={0.5}
      />
    </PageWrapper>
  );
};

export default MasterRankingScreen;
