import { useEffect, useRef } from "react";
import { TextInput, Text, StyleSheet, View, Animated, TouchableOpacity } from "react-native";
import { LIGTHT_THEME } from "../../constants/theme";

interface TextInputProps {
  isPassword?: boolean;
  label: string;
  onChangeText: (text: string) => void;
  value: string;
  onBlur?: () => void;
  errors?: string;
  type?: any;
  editable?: boolean;
}

export const CustomTextInput = (props: TextInputProps) => {
  const { isPassword, label, type, onBlur, errors, value, editable,...rest } = props;
  const labelFocusAnimation = useRef(new Animated.Value(value.length > 0 ? 1 : 0)).current;
  const inputRef = useRef<TextInput>(null);

  const handleFocus = () => {
    Animated.timing(labelFocusAnimation, {
      toValue: 1,
      duration: 200,
      useNativeDriver: false,
    }).start();
  };

  const handleBlur = () => {
    if (!props.value || props.value === "") {
      Animated.timing(labelFocusAnimation, {
        toValue: 0,
        duration: 200,
        useNativeDriver: false,
      }).start();
    }
    onBlur && onBlur();
  };

  return (
    <View style={styles.main_container}>
      <View style={styles.container} >
        <Animated.Text
          style={{
            ...styles.label,
            top: labelFocusAnimation.interpolate({
              inputRange: [0, 1],
              outputRange: [10, -10],
            }),
          }}
        >
          {label}
        </Animated.Text>
        <TextInput
          {...rest}
          editable={editable}
          ref={inputRef}
          value={value}
          textContentType={type}
          onFocus={handleFocus}
          onBlur={handleBlur}
          style={styles.input}
          secureTextEntry={isPassword}
          cursorColor={LIGTHT_THEME.color.black}
        />
      </View>
        {
          errors ? <Text style={{ color: "red" }}>{errors}</Text> : <Text></Text>
        }
    </View>
  );
};

const styles = StyleSheet.create({
  main_container: {
    width: "100%",
  },
  container: {
    width: "100%",
    borderWidth: 1,
    borderRadius: 5,
    borderColor: "black",
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  input: {
    width: "100%",
    height: "100%",
    paddingHorizontal: 10,
  },
  label: {
    position: "absolute",
    left: 10,
    zIndex: 1,
    backgroundColor: LIGTHT_THEME.color.white,
  },
});
