import React, { FC, useEffect, useState, useRef } from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { NavigationProp, useFocusEffect } from '@react-navigation/native';
import { storage, StoreType } from 'src/storage';
import { PageWrapper, Header, Input, WarningModal } from 'src/components';
import { usePostGetGroupMembersQuery, usePostGetGroupSettingsQuery } from '@api/chat';
import { Colors } from 'src/theme';
import UserOptionsModal from '../Components/UserOptionsModal';
import { FlashList } from '@shopify/flash-list';

import SearchIcon from 'assets/icons/search.svg';
import { dataRanking } from '../../TravellersScreen/utils';
import { RankingDropdown, FilterModalRef } from '../../TravellersScreen/utils/types';
import { FilterButton, FilterModal } from '../../TravellersScreen/Components/FilterModal';
import { usePostGetCountriesRanking } from '@api/ranking';
import { Profile } from '../Components/Profile';
import { applyModalSort } from '../applySort';

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

const MembersListScreen: FC<Props> = ({ navigation, route }) => {
  const token = storage.get('token', StoreType.STRING) as string;
  const { groupToken, canChangeAdmin } = route.params;

  const [modalState, setModalState] = useState({
    isWarningVisible: false,
    title: '',
    buttonTitle: '',
    message: '',
    action: () => {}
  });
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const { data, refetch } = usePostGetGroupSettingsQuery(token, groupToken, true);
  const { data: members, refetch: refetchMembers } = usePostGetGroupMembersQuery(
    token,
    groupToken,
    true
  );
  const { data: masterCountries } = usePostGetCountriesRanking();

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

  useFocusEffect(() => {
    navigation.getParent()?.setOptions({
      tabBarStyle: {
        display: 'none'
      }
    });
  });

  useEffect(() => {
    if (members && members.settings && members.settings) {
      setFilteredData(members.settings);
    }
  }, [members]);

  const handleSearch = (text: string) => {
    if (text && members) {
      const searchData =
        members?.settings?.filter((item: any) => {
          const itemData = item.ranking_data
            ? item.ranking_data.first_name.toLowerCase() +
              ' ' +
              item.ranking_data.last_name.toLowerCase()
            : ''.toLowerCase();
          const textData = text.toLowerCase();
          return itemData.indexOf(textData) > -1;
        }) ?? [];
      setFilteredData(searchData);
      setSearchQuery(text);
    } else {
      setFilteredData(members?.settings ?? []);
      setSearchQuery(text);
    }
  };

  return (
    <PageWrapper>
      <Header
        label="Nomads"
        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);
              setFilteredData(
                applyModalSort(
                  (members?.settings as any) ?? [],
                  filterAge,
                  filterRanking ?? dataRanking[0],
                  filterCountry
                )
              );
            }}
            countriesData={masterCountries ? masterCountries.data : []}
          />
        </View>
      </View>
      <View style={styles.container}>
        <Input
          inputMode={'search'}
          placeholder={'Search nomads'}
          onChange={handleSearch}
          value={searchQuery}
          icon={<SearchIcon fill={'#C8C8C8'} width={14} height={14} />}
        />

        <FlashList
          viewabilityConfig={{
            waitForInteraction: true,
            itemVisiblePercentThreshold: 50,
            minimumViewTime: 1000
          }}
          data={filteredData || []}
          renderItem={({ item, index }) => (
            <Profile
              admin={item.admin}
              canChangeAdmin={canChangeAdmin}
              groupToken={groupToken}
              refetch={refetch}
              refetchMembers={refetchMembers}
              setIsWarningVisible={setModalState}
              userId={item.uid}
              key={index}
              index={index}
              first_name={item.ranking_data?.first_name ?? item.name}
              last_name={item.ranking_data?.last_name ?? ''}
              avatar={
                item.ranking_data?.avatar
                  ? '/img/avatars/' + item.ranking_data?.avatar
                  : (item.avatar ?? null)
              }
              date_of_birth={item.ranking_data?.age}
              homebase_flag={'/img/flags_new/' + item.ranking_data?.flag1}
              homebase2_flag={
                item.ranking_data?.flag2 ? '/img/flags_new/' + item.ranking_data?.flag2 : null
              }
              score={[
                item.ranking_data?.score_nm ?? 1,
                item.ranking_data?.score_un ?? 1,
                item.ranking_data?.score_unp ?? 1,
                item.ranking_data?.score_dare,
                item.ranking_data?.score_tcc,
                item.ranking_data?.score_deep,
                item.ranking_data?.score_slow,
                item.ranking_data?.score_yes,
                item.ranking_data?.score_kye,
                item.ranking_data?.score_whs,
                item.ranking_data?.score_tbt
              ]}
              active_score={
                confirmedValueRanking ? confirmedValueRanking.value - 1 : dataRanking[0].value - 1
              }
              tbt_score={item.ranking_data?.score_tbt}
              tbt_rank={item.ranking_data?.rank_tbt}
              badge_tbt={item.ranking_data?.badge_tbt}
              badge_1281={item.ranking_data?.badge_1281}
              badge_un={item.ranking_data?.badge_un}
              badge_un_25={item.ranking_data?.badge_un_25}
              badge_un_50={item.ranking_data?.badge_un_50}
              badge_un_75={item.ranking_data?.badge_un_75}
              badge_un_100={item.ranking_data?.badge_un_100}
              badge_un_150={item.ranking_data?.badge_un_150}
              badge_premium={item.ranking_data?.badge_premium}
              auth={item.ranking_data?.auth}
            />
          )}
          keyExtractor={(item) => item.uid.toString()}
          contentContainerStyle={{ paddingBottom: 16, paddingTop: 8 }}
          showsVerticalScrollIndicator={false}
        />
      </View>

      <WarningModal
        type={'delete'}
        isVisible={modalState.isWarningVisible}
        buttonTitle={modalState.buttonTitle}
        message={modalState.message}
        action={modalState.action}
        onClose={() => setModalState({ ...modalState, isWarningVisible: false })}
        title={modalState.title}
      />
      <UserOptionsModal />
    </PageWrapper>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    gap: 16,
    flex: 1
  },
  avatar: {
    width: 30,
    height: 30,
    borderRadius: 15,
    borderWidth: 1,
    borderColor: Colors.LIGHT_GRAY
  },
  header: {
    paddingTop: 16,
    paddingHorizontal: 6,
    width: 68
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    backgroundColor: Colors.FILL_LIGHT,
    gap: 8,
    borderRadius: 8,
    marginBottom: 6
  }
});

export default MembersListScreen;
