import React, {useEffect, useState} from 'react';
import {StatusBar, StyleSheet, ScrollView, Keyboard} from 'react-native';
import {
  SearchBackground,
  SearchHeader,
  SearchBar,
  Explore,
  SearchResultsBackground,
  SearchResults,
  TabsGradient,
  RecentSearches,
} from '../../components';
import {SCREEN_HEIGHT, StatusBarHeight} from '../../utils';
import Animated, {Easing, timing} from 'react-native-reanimated';
import AsyncStorage from '@react-native-community/async-storage';
import {ProfilePreviewType} from '../../types';
import {SEARCH_ENDPOINT} from '../../constants';
import {AuthContext} from '../../routes/authentication';
import {UserType} from '../../types';
const NO_USER: UserType = {
  userId: '',
  username: '',
};

/**
 * Search Screen for user recommendations and a search
 * tool to allow user to find other users
 */

const SearchScreen: React.FC = () => {
  const {recentSearches} = React.useContext(AuthContext);
  const [query, setQuery] = useState<string>('');
  const [results, setResults] = useState<Array<ProfilePreviewType>>([]);
  const [recents, setRecents] = useState<Array<ProfilePreviewType>>(
    recentSearches,
  );
  const [searching, setSearching] = useState(false);
  const top = Animated.useValue(-SCREEN_HEIGHT);
  const [user, setUser] = useState<UserType>(NO_USER);
  useEffect(() => {
    if (query.length < 3) {
      setResults([]);
      return;
    }
    const loadResults = async (q: string) => {
      try {
        const token = await AsyncStorage.getItem('token');
        if (!token) {
          setUser(NO_USER);
          return;
        }
        const response = await fetch(`${SEARCH_ENDPOINT}?query=${q}`, {
          method: 'GET',
          headers: {
            Authorization: 'Token ' + token,
          },
        });
        const status = response.status;
        if (status === 200) {
          let searchResults = await response.json();
          setResults(searchResults);
          return;
        }
        setResults([]);
      } catch (error) {
        console.log(error);
        setResults([]);
      }
    };
    loadResults(query);
  }, [query]);

  const handleFocus = () => {
    const topInConfig = {
      duration: 180,
      toValue: 0,
      easing: Easing.bezier(0.31, 0.14, 0.66, 0.82),
    };
    timing(top, topInConfig).start();
    setSearching(true);
  };
  const handleBlur = () => {
    Keyboard.dismiss();
    const topOutConfig = {
      duration: 180,
      toValue: -SCREEN_HEIGHT,
      easing: Easing.inOut(Easing.ease),
    };
    timing(top, topOutConfig).start();
    setSearching(false);
  };
  const loadRecentlySearchedUsers = async () => {
    try {
      const asyncCache = await AsyncStorage.getItem('@recently_searched_users');
      asyncCache != null ? setRecents(JSON.parse(asyncCache)) : setRecents([]);
    } catch (e) {
      console.log(e);
    }
  };
  const clearRecentlySearched = async () => {
    try {
      await AsyncStorage.removeItem('@recently_searched_users');
      loadRecentlySearchedUsers();
    } catch (e) {
      console.log(e);
    }
  };
  const handleUpdate = async (val: string) => {
    setQuery(val);
    loadRecentlySearchedUsers();
  };

  return (
    <SearchBackground>
      <StatusBar />
      <ScrollView
        scrollEnabled={!searching}
        keyboardShouldPersistTaps={'always'}
        stickyHeaderIndices={[4]}
        contentContainerStyle={styles.contentContainer}
        showsVerticalScrollIndicator={false}>
        <SearchHeader style={styles.header} {...{top}} />
        <SearchBar
          style={styles.searchBar}
          onCancel={handleBlur}
          onChangeText={handleUpdate}
          onBlur={Keyboard.dismiss}
          onFocus={handleFocus}
          value={query}
          {...{top, searching}}
        />
        <Explore />
        <SearchResultsBackground {...{top}}>
          {results.length === 0 && recents.length !== 0 ? (
            <RecentSearches
              sectionTitle="Recent"
              sectionButtonTitle="Clear all"
              onPress={clearRecentlySearched}
              recents={recents}
            />
          ) : (
            <SearchResults {...{results}} />
          )}
        </SearchResultsBackground>
      </ScrollView>
      <TabsGradient />
    </SearchBackground>
  );
};

const styles = StyleSheet.create({
  contentContainer: {
    paddingTop: StatusBarHeight,
    paddingBottom: SCREEN_HEIGHT / 15,
    paddingHorizontal: 15,
  },
  searchBar: {
    marginBottom: 20,
  },
  header: {
    marginVertical: 20,
    zIndex: 1,
  },
  recentsHeaderContainer: {
    flexDirection: 'row',
  },
  recentsHeader: {
    fontSize: 17,
    fontWeight: 'bold',
    flexGrow: 1,
  },
  clear: {
    fontSize: 17,
    fontWeight: 'bold',
    color: '#698DD3',
  },
});
export default SearchScreen;
