import { NavigationProp } from '@react-navigation/native';
import React, { FC, useCallback, useEffect, useState } from 'react';
import { ActivityIndicator } 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 } from '../../TravellersScreen/utils/types';
import { dataRanking } from '../../TravellersScreen/utils';
import { Ranking } from '../../TravellersScreen';
import { useGetFriendsMutation } from '@api/friends';
import { useGetUsersFromCountryMutation, useGetUsersWhoVisitedCountryMutation } from '@api/countries';

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

const UsersListScreen: FC<Props> = ({ navigation, route }) => {
  const id = route.params?.id;
  const type = route.params?.type;
  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 [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 [isModalVisible, setModalVisible] = useState(false);
  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 {
        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 {
      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: '' }];
    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' : 'Been here'}
        rightElement={<FilterButton onPress={() => setModalVisible(!isModalVisible)} />}
      />
      <FlashList
        viewabilityConfig={{
          waitForInteraction: true,
          itemVisiblePercentThreshold: 50,
          minimumViewTime: 1000
        }}
        estimatedItemSize={50}
        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}
            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} />}
      />

      <FilterModal
        isModalVisible={isModalVisible}
        setModalVisible={(value) => setModalVisible(value)}
        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
          });
          setModalVisible(false);
        }}
        countriesData={masterCountries}
        isCountryHidden={isFromHere}
      />
    </PageWrapper>
  );
};

export default UsersListScreen;
