import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Image } from 'react-native';
import { TabView, TabBar } from 'react-native-tab-view';
import ReactModal from 'react-native-modal';
import { FlashList } from '@shopify/flash-list';
import { useNavigation } from '@react-navigation/native';

import { Colors } from 'src/theme';
import { styles } from './styles';
import { NAVIGATION_PAGES } from 'src/types';
import { API_HOST } from 'src/constants';
import { Loading, WarningModal } from 'src/components';
import { StoreType, storage } from 'src/storage';

const SearchModal = ({
  searchVisible,
  handleCloseModal,
  handleFindRegion,
  index,
  searchData,
  setIndex,
  token
}: {
  searchVisible: boolean;
  handleCloseModal: () => void;
  handleFindRegion: (id: number, type: 'regions' | 'countries' | 'places') => void;
  index: number;
  searchData: any;
  setIndex: (index: number) => void;
  token: string | undefined;
}) => {
  const navigation = useNavigation();
  const [routes] = useState([
    { key: 'users', title: 'Nomads' },
    { key: 'regions', title: 'NM regions' },
    { key: 'dare', title: 'DARE places' }
  ]);
  const [shouldOpenModal, setShouldOpenModal] = useState<{
    id: number;
    type: 'regions' | 'countries' | 'places';
  } | null>(null);
  const [warningVisible, setWarningVisible] = useState(false);

  const renderItem = ({ item }: { item: any }) => {
    const [name, ...rest] = item.name?.split(/ – | - /);
    const subname = rest?.join(' - ');

    return index === 0 ? (
      <TouchableOpacity
        style={{ paddingVertical: 12 }}
        onPress={() => {
          if (!token) {
            setWarningVisible(true);
          } else {
            handleCloseModal();
            navigation.navigate(
              ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: item.id }] as never)
            );
          }
        }}
      >
        <View style={styles.container}>
          <Image
            source={
              item.avatar
                ? { uri: API_HOST + item.avatar }
                : require('../../../../../assets/logo-ua.png')
            }
            style={styles.img}
          />
          <View style={styles.textContainer}>
            <Text style={styles.title}>{item.name}</Text>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Image source={{ uri: API_HOST + item.flag1 }} style={styles.flagSmall} />
              {item.flag2 && item.flag2 !== item.flag1 && (
                <Image
                  source={{ uri: API_HOST + item.flag2 }}
                  style={[
                    styles.flagSmall,
                    {
                      marginLeft: -6
                    }
                  ]}
                />
              )}
            </View>
          </View>
        </View>
      </TouchableOpacity>
    ) : (
      <TouchableOpacity
        style={{ paddingVertical: 12 }}
        onPress={() => {
          handleCloseModal();
          if (index === 1) {
            setShouldOpenModal({ id: item.id, type: 'regions' });
          } else {
            setShouldOpenModal({ id: item.id, type: 'places' });
          }
        }}
      >
        <View style={styles.container}>
          {item.flag1 && <Image source={{ uri: API_HOST + item.flag1 }} style={styles.img} />}
          {item.flag2 && (
            <Image
              source={{ uri: API_HOST + item.flag2 }}
              style={[
                styles.img,
                {
                  marginLeft: -20
                }
              ]}
            />
          )}
          <View style={styles.textContainer}>
            <Text style={styles.title}>{name}</Text>
            <Text style={styles.subTitle}>{subname}</Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  const renderScene = ({ route }: { route: any }) => {
    return (
      <View style={{ flex: 1 }}>
        {searchData?.[route.key] ? (
          <FlashList
            viewabilityConfig={{
              waitForInteraction: true,
              itemVisiblePercentThreshold: 50,
              minimumViewTime: 1000
            }}
            estimatedItemSize={45}
            data={searchData?.[route.key]}
            renderItem={renderItem}
            keyExtractor={(item) => item.id.toString()}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={{ paddingVertical: 16, paddingHorizontal: 8 }}
          />
        ) : (
          <Loading />
        )}
        <WarningModal
          type="unauthorized"
          isVisible={warningVisible}
          onClose={() => setWarningVisible(false)}
          action={handleCloseModal}
        />
      </View>
    );
  };

  return (
    <ReactModal
      isVisible={searchVisible}
      onBackdropPress={handleCloseModal}
      onBackButtonPress={handleCloseModal}
      style={styles.modal}
      statusBarTranslucent={true}
      presentationStyle="overFullScreen"
      onModalHide={() => {
        if (shouldOpenModal) {
          handleFindRegion(shouldOpenModal.id, shouldOpenModal.type);
          setShouldOpenModal(null);
        }
      }}
    >
      <View style={styles.modalContainer}>
        <TabView
          navigationState={{ index, routes }}
          renderScene={renderScene}
          onIndexChange={setIndex}
          lazy={true}
          renderTabBar={(props) => (
            <TabBar
              {...props}
              indicatorStyle={{ backgroundColor: Colors.DARK_BLUE }}
              style={styles.tabBar}
              tabStyle={styles.tabStyle}
              pressColor={'transparent'}
              renderLabel={({ route, focused }) => (
                <Text
                  style={[styles.tabLabel, { color: Colors.DARK_BLUE, opacity: focused ? 1 : 0.4 }]}
                >
                  {route.title}
                </Text>
              )}
            />
          )}
        />
      </View>
    </ReactModal>
  );
};

export default SearchModal;
