import React, {useState} from 'react';
import {
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Text,
  View,
  TextInputProps,
  Keyboard,
  NativeSyntheticEvent,
  TextInputSubmitEditingEventData,
} from 'react-native';
import Animated, {interpolate} from 'react-native-reanimated';
import Icon from 'react-native-vector-icons/Feather';
import {normalize} from 'react-native-elements';
import {SCREEN_HEIGHT} from '../../utils';

const AnimatedIcon = Animated.createAnimatedComponent(Icon);

interface SearchBarProps extends TextInputProps {
  onCancel: () => void;
  top: Animated.Value<number>;
}
const SearchBar: React.FC<SearchBarProps> = ({
  onFocus,
  onBlur,
  onChangeText,
  value,
  onCancel,
  top,
}) => {
  const handleSubmit = (
    e: NativeSyntheticEvent<TextInputSubmitEditingEventData>,
  ) => {
    e.preventDefault();
    Keyboard.dismiss();
  };

  /*
   * CSS properties for width change animation.
   */
  const marginRight: Animated.Node<number> = interpolate(top, {
    inputRange: [-SCREEN_HEIGHT, 0],
    outputRange: [0, 58],
  });
  const opacity: Animated.Node<number> = interpolate(top, {
    inputRange: [-SCREEN_HEIGHT, 0],
    outputRange: [0, 1],
  });

  return (
    <View style={styles.container}>
      <Animated.View style={styles.inputContainer}>
        <AnimatedIcon
          name="search"
          color={'#7E7E7E'}
          size={25}
          style={styles.searchIcon}
        />
        <TextInput
          style={[styles.input]}
          placeholder={'Search'}
          placeholderTextColor={'#828282'}
          onSubmitEditing={handleSubmit}
          clearButtonMode="while-editing"
          autoCapitalize="none"
          autoCorrect={false}
          {...{value, onChangeText, onFocus, onBlur}}
        />
      </Animated.View>
      <Animated.View style={{marginRight, opacity}}>
        <TouchableOpacity style={styles.cancelButton} onPress={onCancel}>
          <Text style={styles.cancelText}>Cancel</Text>
        </TouchableOpacity>
      </Animated.View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: 40,
    paddingHorizontal: 20,
    flexDirection: 'row',
  },
  inputContainer: {
    flexGrow: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    borderRadius: 20,
    backgroundColor: '#F0F0F0',
  },
  searchIcon: {
    marginRight: 8,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: '#000',
    letterSpacing: normalize(0.5),
  },
  cancelButton: {
    height: '100%',
    position: 'absolute',
    justifyContent: 'center',
    paddingHorizontal: 8,
  },
  cancelText: {
    color: '#818181',
    fontWeight: '500',
  },
});

export default SearchBar;
