import React, { FC, useEffect, useState, useRef } from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { NavigationProp } from '@react-navigation/native';
import { PageWrapper, Header, Input, WarningModal } from 'src/components';
import { FlashList } from '@shopify/flash-list';

import SearchIcon from 'assets/icons/search.svg';
import { applyModalSort, dataRanking } from '../../TravellersScreen/utils';
import { RankingDropdown, FilterModalRef } from '../../TravellersScreen/utils/types';
import { Profile } from '../../MapScreen/UsersListScreen/Profile';
import { FilterButton, FilterModal } from '../../TravellersScreen/Components/FilterModal';
import { usePostGetCountriesRanking } from '@api/ranking';
import OptionsModal from '../Components/OptionsModal';
import { SheetManager } from 'react-native-actions-sheet';
import { storage, StoreType } from 'src/storage';

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

const ParticipantsListScreen: FC<Props> = ({ navigation, route }) => {
  const { participants, eventId, isHost, interested, isTrip } = route.params;
  const token = storage.get('token', StoreType.STRING);
  const { data: masterCountries } = usePostGetCountriesRanking();

  const [allParticipants, setAllParticipants] = useState(participants);
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const [confirmedValueRanking, setConfirmedValueRanking] = useState<RankingDropdown | null>();
  const filterRef = useRef<FilterModalRef>(null);
  const [modalState, setModalState] = useState({
    isWarningVisible: false,
    title: '',
    buttonTitle: '',
    message: '',
    action: () => {}
  });

  useEffect(() => {
    if (allParticipants) {
      setFilteredData(allParticipants);
    }
  }, [allParticipants]);

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

  const handleFilterParticipants = (userId: number) => {
    setAllParticipants(allParticipants.filter((p: any) => p.user_id !== userId));
  };

  const handleOptionPress = (user: any) => {
    SheetManager.show('host-options-modal', {
      payload: {
        eventId,
        userId: user.user_id,
        name: user.first_name + ' ' + user.last_name,
        token,
        filterParticipants: () => handleFilterParticipants(user.user_id),
        setIsWarningVisible: setModalState,
        interested: interested,
        isTrip: isTrip
      } as any
    });
  };

  return (
    <PageWrapper>
      <Header
        label={interested ? 'Interested' : 'Going'}
        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(
                  allParticipants ?? [],
                  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
              withMenu={isHost}
              onPressOption={() => handleOptionPress(item)}
              userId={item.user_id}
              key={index}
              index={index}
              first_name={item.first_name}
              last_name={item.last_name}
              avatar={item.avatar ? '/img/avatars/' + item.avatar : null}
              date_of_birth={item.age}
              homebase_flag={'/img/flags_new/' + item.flag1}
              homebase2_flag={item.flag2 ? '/img/flags_new/' + item.flag2 : null}
              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}
        />
      </View>
      <OptionsModal />
      <WarningModal
        type={'delete'}
        isVisible={modalState.isWarningVisible}
        buttonTitle={modalState.buttonTitle}
        message={modalState.message}
        action={modalState.action}
        onClose={() => setModalState({ ...modalState, isWarningVisible: false })}
        title={modalState.title}
      />
    </PageWrapper>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    gap: 16,
    flex: 1
  }
});

export default ParticipantsListScreen;
