import React, { useEffect, useState, useRef } from 'react';
import { TouchableOpacity, View, Text, Dimensions } from 'react-native';
import { FlashList } from '@shopify/flash-list';

import { useGetMaster, usePostGetCountriesRanking } from '@api/ranking';
import { Header, Loading, PageWrapper } from '../../../../components';
import { Profile } from '../Components/Profile';
import { FilterModal, FilterButton } from '../Components/FilterModal';

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

import type { Ranking } from '..';

import ChevronLeft from 'assets/icons/chevron-left.svg';
import { Colors } from 'src/theme';
import { getFontSize } from 'src/utils';

const MasterRankingScreen = () => {
  const { data: masterCountries } = usePostGetCountriesRanking();

  const [masterRanking, setMasterRanking] = useState<Ranking[]>([]);
  const filterRef = useRef<FilterModalRef>(null);
  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();
  const [filter, setFilter] = useState({
    age: 0,
    ranking: dataRanking[0].name,
    country: 'ALL'
  });
  const [page, setPage] = useState(0);
  const [first, setFirst] = useState(0);
  const [last, setLast] = useState(0);

  const { data } = useGetMaster(filter.country, filter.age, filter.ranking, 50, page, true);

  useEffect(() => {
    if (data && data.data) {
      let indexCounter = data.data.first - 1;

      setMasterRanking(
        data.data.ranking.map((item) => {
          return item.dod !== 1
            ? { ...item, displayIndex: indexCounter++ }
            : { ...item, displayIndex: -1 };
        })
      );
      const filtered = data.data.ranking.filter((item) => item.dod !== 1);
      setFirst(data.data.ranking.length ? data.data.first : 0);
      setLast(filtered.length + data.data.first - 1);
    }
  }, [data]);

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

      <View style={{ zIndex: 100 }}>
        <View
          style={{
            position: 'absolute',
            top: -10,
            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);
              setFilter({
                age: filterAge?.value ? +filterAge?.value : 0,
                ranking: filterRanking ? filterRanking.name : dataRanking[0].name,
                country: filterCountry?.two ? filterCountry.two?.toLowerCase() : 'ALL'
              });
              setPage(0);
            }}
            countriesData={masterCountries ? masterCountries.data : []}
          />
        </View>
      </View>

      <View
        style={{
          marginTop: '-5%',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <TouchableOpacity
          style={{
            width: 52,
            height: 30,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
          onPress={() => setPage((prev) => prev - 1)}
          disabled={page === 0}
        >
          <ChevronLeft fill={page === 0 ? Colors.LIGHT_GRAY : Colors.DARK_BLUE} height={12} />
        </TouchableOpacity>

        <Text
          style={{
            fontFamily: 'redhat-700',
            fontSize: getFontSize(14),
            color: Colors.DARK_BLUE,
            textAlign: 'center'
          }}
        >
          {first} - {last}
        </Text>

        <TouchableOpacity
          style={{
            width: 52,
            height: 30,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
          onPress={() => setPage((prev) => prev + 1)}
          disabled={data?.data?.max === page + 1}
        >
          <ChevronLeft
            fill={data?.data?.max === page + 1 ? Colors.LIGHT_GRAY : Colors.DARK_BLUE}
            height={12}
            style={{ transform: [{ rotate: '180deg' }] }}
          />
        </TouchableOpacity>
      </View>
      {data && data.data ? (
        <FlashList
          showsVerticalScrollIndicator={false}
          data={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}
              badge_premium={item.badge_premium}
              auth={item.auth}
            />
          )}
          viewabilityConfig={{
            waitForInteraction: true,
            itemVisiblePercentThreshold: 50,
            minimumViewTime: 1000
          }}
          contentContainerStyle={{ paddingTop: 8 }}
        />
      ) : (
        <View style={{ flex: 1 }}>
          <Loading />
        </View>
      )}
    </PageWrapper>
  );
};

export default MasterRankingScreen;
