import React, { useEffect, useRef, useState } from "react";
import {
  TextInput,
  Text,
  StyleSheet,
  View,
  Animated,
  TouchableOpacity,
  TextInputProps,
} from "react-native";
import { LIGHT_THEME } from "../../const/theme";
import { Feather } from "@expo/vector-icons";

interface CustomTextInputProps {
  isPassword?: boolean;
  label: string;
  value: string;
  onBlur?: () => void;
  errors?: string;
  editable?: boolean;
  textInputProps?: TextInputProps;
  alwaysOpen?: boolean;
}

export const CustomTextInput = ({
  textInputProps,
  label,
  value,
  errors,
  onBlur,
  editable,
  isPassword,
  alwaysOpen = false,
}: CustomTextInputProps) => {
  const labelFocusAnimation = useRef(
    new Animated.Value(value.length > 0 || alwaysOpen ? 1 : 0)
  ).current;
  const inputRef = useRef<TextInput>(null);
  const [showPassword, setShowPassword] = useState(false);

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

  const handleBlur = () => {
    if (!alwaysOpen && (!value || 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
          {...textInputProps}
          editable={editable}
          ref={inputRef}
          value={value}
          onFocus={handleFocus}
          onBlur={handleBlur}
          style={styles.input}
          secureTextEntry={isPassword && !showPassword}
          cursorColor={LIGHT_THEME.color.black}
        />
        {isPassword && (
          <Feather
            name={showPassword ? "eye-off" : "eye"}
            size={24}
            color={LIGHT_THEME.color.black}
            style={styles.showPassword}
            onPress={() => setShowPassword(!showPassword)}
          />
        )}
      </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: LIGHT_THEME.color.white,
  },
  showPassword: {
    position: "absolute",
    right: 10,
    zIndex: 2,
  },
});
