import {useNavigation} from '@react-navigation/core';
import React, {useEffect, useRef, useState} from 'react';
import {
  Keyboard,
  SectionListData,
  StatusBar,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {useSharedValue} from 'react-native-reanimated';
import {BottomDrawer} from '../../components';
import {SEARCH_ENDPOINT} from '../../constants';
import {loadSearchResults} from '../../services';
import {ScreenType} from '../../types';
import {normalize} from '../../utils';
import {ChatResultsList, ChatSearchBar} from './index';
interface NewChatModalProps {
  setChatModalVisible: (open: boolean) => void;
}

const NewChatModal: React.FC<NewChatModalProps> = ({setChatModalVisible}) => {
  const [modalVisible, setModalVisible] = useState(true);
  const navigation = useNavigation();
  const sheetRef = useRef(null);
  const [searching, setSearching] = useState(false);
  /*
   * Animated value
   */
  const animationProgress = useSharedValue<number>(0);
  const [results, setResults] = useState<SectionListData<any>[]>([]);
  const [query, setQuery] = useState<string>('');
  const handleFocus = () => {
    setSearching(true);
  };
  const handleBlur = () => {
    Keyboard.dismiss();
  };
  const handleCancel = () => {
    setSearching(false);
  };

  useEffect(() => {
    if (!searching) {
      return;
    }
    if (query.length < 3) {
      return;
    }
    (async () => {
      const searchResults = await loadSearchResults(
        `${SEARCH_ENDPOINT}?query=${query}`,
      );
      if (query.length > 2) {
        const sanitizedResult = [
          {
            title: 'users',
            data: searchResults?.users,
          },
        ];
        setResults(sanitizedResult);
      } else {
        setResults([]);
      }
    })();
  }, [query]);

  const _modalContent = () => {
    return (
      <View style={styles.modalShadowContainer}>
        <View style={styles.titleContainerStyles}>
          <Text style={styles.titleTextStyles}>New Message</Text>
        </View>
        <ChatSearchBar
          onCancel={handleCancel}
          onChangeText={setQuery}
          onBlur={handleBlur}
          onFocus={handleFocus}
          value={query}
          {...{animationProgress, searching}}
          placeholder={''}
        />
        {results.length > 0 && (
          <View style={styles.headerContainerStyles}>
            <Text style={styles.headerTextStyles}>Suggested</Text>
          </View>
        )}
        <ChatResultsList
          {...{results, setChatModalVisible}}
          previewType={'Search'}
          screenType={ScreenType.Search}
        />
      </View>
    );
  };

  return (
    <View>
      <StatusBar barStyle="dark-content" />
      <BottomDrawer
        initialSnapPosition={'90%'}
        isOpen={modalVisible}
        enabledContentGestureInteraction={true}
        setIsOpen={setChatModalVisible}
        showHeader={false}>
        {_modalContent()}
      </BottomDrawer>
    </View>
  );
};

const styles = StyleSheet.create({
  modalShadowContainer: {
    height: '100%',
    borderRadius: 9,
    backgroundColor: 'white',
  },
  titleContainerStyles: {marginVertical: 24},
  titleTextStyles: {
    fontWeight: 'bold',
    fontSize: normalize(18),
    lineHeight: normalize(21),
    textAlign: 'center',
  },
  headerContainerStyles: {
    marginTop: 26,
    marginBottom: 10,
    marginHorizontal: 28,
  },
  headerTextStyles: {
    fontWeight: 'bold',
    fontSize: normalize(17),
    lineHeight: normalize(20),
  },
});

export default NewChatModal;
