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

const AnimatedTextInput = Animated.createAnimatedComponent(TextInput);

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,
  style,
}) => {
  const opacity: Animated.Node<number> = interpolate(top, {
    inputRange: [-SCREEN_HEIGHT, 0],
    outputRange: [0, 1],
  });
  const marginRight: Animated.Node<number> = interpolate(top, {
    inputRange: [-SCREEN_HEIGHT, 0],
    outputRange: [0, 57],
  });
  const color: Animated.Node<number> = interpolateColors(top, {
    inputRange: [-SCREEN_HEIGHT, 0],
    outputColorRange: ['#fff', '#000'],
  });
  const handleSubmit = (
    e: NativeSyntheticEvent<TextInputSubmitEditingEventData>,
  ) => {
    e.preventDefault();
    Keyboard.dismiss();
  };

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

const styles = StyleSheet.create({
  container: {
    height: 40,
    flexDirection: 'row',
    alignItems: 'stretch',
    zIndex: 2,
  },
  inputContainer: {
    flexGrow: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    borderWidth: 1.5,
    borderRadius: 20,
    backgroundColor: '#fff3',
  },
  searchIcon: {
    marginRight: 8,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: '#fff',
  },
  cancelButton: {
    position: 'absolute',
    height: '100%',
    justifyContent: 'center',
    paddingHorizontal: 5,
  },
  cancelText: {
    color: '#818181',
    fontWeight: '600',
  },
});

export default SearchBar;
