import React, { useCallback, useEffect, useRef, useState } from 'react';
import { View, Text, TouchableOpacity, Image, Dimensions } from 'react-native';
import { FlashList } from '@shopify/flash-list';
import { useNavigation } from '@react-navigation/native';

import { styles } from './styles';
import { NAVIGATION_PAGES } from 'src/types';
import { API_HOST } from 'src/constants';
import { Loading, WarningModal } from 'src/components';
import MessagesDot from 'src/components/MessagesDot';
import ActionSheet, { ActionSheetRef } from 'react-native-actions-sheet';
import TabViewWrapper from 'src/components/TabViewWrapper';

export function TabViewDelayed({
  children,
  waitBeforeShow = 0
}: {
  children: React.ReactNode;
  waitBeforeShow?: number;
}) {
  const [isShown, setIsShown] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShown(true);
    }, waitBeforeShow);
    return () => clearTimeout(timer);
  }, [waitBeforeShow]);

  return isShown ? children : null;
}

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 actionSheetRef = useRef<ActionSheetRef>(null);
  const modalHeight = Dimensions.get('window').height * 0.75;

  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);

  useEffect(() => {
    if (searchVisible) {
      actionSheetRef.current?.show();
    } else {
      if (actionSheetRef.current?.isOpen()) {
        actionSheetRef.current?.hide();
      }
    }
  }, [searchVisible]);

  useEffect(() => {
    if (!searchData) return;

    if (searchData['users'] && searchData['users'].length > 0) {
      setIndex(0);
    } else if (searchData['regions'] && searchData['regions'].length > 0) {
      setIndex(1);
    } else if (searchData['dare'] && searchData['dare'].length > 0) {
      setIndex(2);
    } else {
      setIndex(0);
    }
  }, [searchData]);

  const renderItem = useCallback(
    ({ 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-world.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>
      );
    },
    [index]
  );

  const renderScene = ({ route }: { route: any }) => {
    return (
      <View style={{ flex: 1 }}>
        {searchData?.[route.key] ? (
          <FlashList
            viewabilityConfig={{
              waitForInteraction: true,
              itemVisiblePercentThreshold: 50,
              minimumViewTime: 1000
            }}
            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 (
    <ActionSheet
      ref={actionSheetRef}
      onClose={() => {
        handleCloseModal();
        if (shouldOpenModal) {
          handleFindRegion(shouldOpenModal.id, shouldOpenModal.type);
          setShouldOpenModal(null);
        }
      }}
      containerStyle={styles.modal}
      gestureEnabled={false}
      defaultOverlayOpacity={0.5}
    >
      <View style={[styles.modalContainer, { height: modalHeight }]}>
        {searchVisible && (
          <TabViewDelayed waitBeforeShow={300}>
            <TabViewWrapper
              routes={routes}
              renderScene={renderScene}
              setIndex={setIndex}
              selectedIndex={index}
              renderBadge={({ route }) =>
                searchData?.[route.key] && searchData?.[route.key].length > 0 ? (
                  <MessagesDot messagesCount={searchData?.[route.key].length} top={4} />
                ) : null
              }
              lazy={false}
            />
          </TabViewDelayed>
        )}
      </View>
    </ActionSheet>
  );
};

export default SearchModal;
