import { NavigationProp } from '@react-navigation/native';
import React, { FC, useCallback, useEffect, useState, useRef } from 'react';
import { ActivityIndicator, Dimensions, View } from 'react-native';
import { Header, Loading, PageWrapper } from 'src/components';

import { Colors } from 'src/theme';
import { FlashList } from '@shopify/flash-list';
import { StoreType, storage } from 'src/storage';
import { FilterButton, FilterModal } from '../../TravellersScreen/Components/FilterModal';
import {
  useGetUsersFromRegionMutation,
  useGetUsersWhoVisitedDareMutation,
  useGetUsersWhoVisitetRegionMutation
} from '@api/regions';
import { Profile } from './Profile';
import { RankingDropdown, FilterModalRef } from '../../TravellersScreen/utils/types';
import { dataRanking } from '../../TravellersScreen/utils';
import { Ranking } from '../../TravellersScreen';
import { useGetFriendsMutation } from '@api/friends';
import {
  useGetUsersFromCountryMutation,
  useGetUsersWhoVisitedCountryMutation
} from '@api/countries';
import { useGetUsersWhoTickesSeriesMutation } from '@api/series';

type Props = {
  navigation: NavigationProp<any>;
  route: any;
};

const UsersListScreen: FC<Props> = ({ navigation, route }) => {
  const id = route.params?.id;
  const type = route.params?.type;
  const token = storage.get('token', StoreType.STRING) as string;
  const { mutateAsync: getUsersFromRegion } = useGetUsersFromRegionMutation();
  const { mutateAsync: getUsersWhoVisitedRegion } = useGetUsersWhoVisitetRegionMutation();
  const { mutateAsync: getUsersWhoVisitedDare } = useGetUsersWhoVisitedDareMutation();
  const { mutateAsync: getUsersFromCountry } = useGetUsersFromCountryMutation();
  const { mutateAsync: getUsersWhoVisitedCountry } = useGetUsersWhoVisitedCountryMutation();
  const { mutateAsync: getFriends } = useGetFriendsMutation();
  const { mutateAsync: getUsersWhoTickedSeries } = useGetUsersWhoTickesSeriesMutation();
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedUsers, setSelectedUsers] = useState<any[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<Ranking[]>([]);
  const isFromHere = route.params?.isFromHere;
  const filterRef = useRef<FilterModalRef>(null);
  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();
  const [masterCountries, setMasterCountries] = useState<any>([]);
  const [maxPages, setMaxPages] = useState(1);
  const [page, setPage] = useState(0);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [filter, setFilter] = useState<{
    age: number | undefined;
    ranking: string | undefined;
    country: string | undefined;
  }>({ age: undefined, ranking: undefined, country: undefined });

  useEffect(() => {
    setFilteredUsers(selectedUsers);
  }, [selectedUsers]);

  useEffect(() => {
    applySort();
  }, [filter]);

  useEffect(() => {
    const getNextPage = async () => {
      if (isFromHere && type === 'nm') {
        await getUsersFromRegion(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else if (type === 'nm') {
        await getUsersWhoVisitedRegion(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age,
            country: filter.country
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else if (type === 'friends') {
        await getFriends(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age,
            country: filter.country
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else if (isFromHere && type === 'country') {
        await getUsersFromCountry(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else if (type === 'country') {
        await getUsersWhoVisitedCountry(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age,
            country: filter.country
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else if (type === 'series') {
        await getUsersWhoTickedSeries(
          {
            token,
            id,
            page,
            sort: filter.ranking,
            age: filter.age,
            country: filter.country
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      } else {
        await getUsersWhoVisitedDare(
          {
            id,
            page,
            sort: filter.ranking,
            age: filter.age,
            country: filter.country
          },
          {
            onSuccess: (data) => {
              setIsLoadingMore(false);
              setUsers((prevState) => [...prevState, ...data?.data?.users]);
              setSelectedUsers((prevState) => [...prevState, ...data?.data?.users]);
            }
          }
        );
      }
    };
    if (page !== 0) {
      getNextPage();
    }
  }, [page]);

  const applySort = async () => {
    if (isFromHere && type === 'nm') {
      await getUsersFromRegion(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            setLoading(false);
          }
        }
      );
    } else if (type === 'nm') {
      await getUsersWhoVisitedRegion(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age,
          country: filter.country
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            !masterCountries.length && setMasterCountries(convertData(data?.data?.countries) ?? []);
            setLoading(false);
          }
        }
      );
    } else if (isFromHere && type === 'country') {
      await getUsersFromCountry(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            setLoading(false);
          }
        }
      );
    } else if (type === 'country') {
      await getUsersWhoVisitedCountry(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age,
          country: filter.country
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            !masterCountries?.length &&
              setMasterCountries(convertData(data?.data?.countries) ?? []);
            setLoading(false);
          }
        }
      );
    } else if (type === 'friends') {
      await getFriends(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age,
          country: filter.country
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            !masterCountries?.length &&
              setMasterCountries(convertData(data?.data?.countries) ?? []);
            setLoading(false);
          }
        }
      );
    } else if (type === 'series') {
      await getUsersWhoTickedSeries(
        {
          token,
          id,
          page,
          sort: filter.ranking,
          age: filter.age,
          country: filter.country
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            !masterCountries?.length &&
              setMasterCountries(convertData(data?.data?.countries) ?? []);
            setLoading(false);
          }
        }
      );
    } else {
      await getUsersWhoVisitedDare(
        {
          id,
          page,
          sort: filter.ranking,
          age: filter.age,
          country: filter.country
        },
        {
          onSuccess: (data) => {
            setUsers(data?.data?.users);
            setSelectedUsers(data?.data?.users);
            setMaxPages(data?.data?.max_pages);
            !masterCountries?.length &&
              setMasterCountries(convertData(data?.data?.countries) ?? []);
            setLoading(false);
          }
        }
      );
    }
  };

  const convertData = (data: { [key: string]: { country: string; flag: string } }) => {
    let formatedCountries = [{ two: 'all', name: 'ALL', flag: '' }];
    data &&
      formatedCountries.push(
        ...Object.entries(data).map(([key, value]) => ({
          two: key,
          name: value.country,
          flag: value.flag
        }))
      );

    return formatedCountries;
  };

  const handleEndReached = useCallback(() => {
    if (users && page < maxPages && !isLoadingMore) {
      setIsLoadingMore(true);
      setPage((prevPage) => prevPage + 1);
    }
  }, [users, page]);

  if (loading) return <Loading />;

  const ListFooter = ({ isLoading }: { isLoading: boolean }) =>
    isLoading ? <ActivityIndicator size="large" color={Colors.DARK_BLUE} /> : null;

  return (
    <PageWrapper>
      <Header
        label={
          isFromHere
            ? 'From here'
            : type === 'friends'
              ? 'Friends'
              : type === 'series'
                ? 'Completed'
                : 'Been here'
        }
        rightElement={<FilterButton onPress={() => filterRef.current?.toggle()} />}
      />

      <View style={{ zIndex: 100 }}>
        <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);
              setPage(0);
              setFilter({
                age: filterAge?.value ? +filterAge?.value : undefined,
                ranking: filterRanking?.name,
                country:
                  filterCountry?.two && filterCountry?.two !== 'all'
                    ? filterCountry?.two
                    : undefined
              });
            }}
            countriesData={masterCountries}
            isCountryHidden={isFromHere}
          />
        </View>
      </View>
      <FlashList
        viewabilityConfig={{
          waitForInteraction: true,
          itemVisiblePercentThreshold: 50,
          minimumViewTime: 1000
        }}
        data={filteredUsers}
        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,
              item.score_tbt
            ]}
            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}
          />
        )}
        keyExtractor={(item) => item.user_id.toString()}
        contentContainerStyle={{ paddingBottom: 16, paddingTop: 8 }}
        showsVerticalScrollIndicator={false}
        onEndReached={handleEndReached}
        onEndReachedThreshold={0.2}
        ListFooterComponent={<ListFooter isLoading={isLoadingMore} />}
      />
    </PageWrapper>
  );
};

export default UsersListScreen;
