import {
  StyleSheet,
  TextInput,
  TouchableWithoutFeedback,
  View,
  Platform,
} from 'react-native';
import React, { useRef, useState } from 'react';
import type { Theme, RsTextStyle, RsTextInputProps } from '../styles/types';
import { useTheme } from '../hooks/ThemeProvider';
import { useMemo } from 'react';

const RsTextInput: React.FC<RsTextInputProps & RsTextStyle> = ({
  value = '',
  placeholder = '',
  onChangeText = () => {},
  onFocus,
  onBlur,
  containerStyle = undefined,
  fontSize = 14,
  fontWeight = 'Regular',
  textAlign = 'left',
  textTransform = 'none',
  color,
  style,
  ...props
}) => {
  const [isFocused, setIsFocused] = useState(false);
  const [inputValue, setInputValue] = useState(value);
  const inputRef = useRef<TextInput>(null);

  const theme = useTheme();
  const styles = useMemo(
    () =>
      generateStyles(theme, {
        fontSize,
        fontWeight,
        textAlign,
        textTransform,
        color,
      }, isFocused),
    [theme, fontSize, fontWeight, textAlign, textTransform, color, isFocused]
  );

  return (
    <TouchableWithoutFeedback onPress={() => inputRef.current?.focus()}>
      <View style={containerStyle ?? styles.container}>
        <TextInput
          ref={inputRef}
          value={inputValue}
          placeholder={placeholder}
          placeholderTextColor={theme.Text.inputPlaceholder}
          onChangeText={(text) => {
            setInputValue(text);
            onChangeText(text);
          }}
          style={style ?? styles.input}
          onFocus={(e) => {
            setIsFocused(true);
            onFocus && onFocus(e);
          }}
          onBlur={(e) => {
            setIsFocused(false);
            onBlur && onBlur(e);
          }}
          submitBehavior="blurAndSubmit"
          selectionColor={theme.Borders.inputActive}
          {...props}
        />
      </View>
    </TouchableWithoutFeedback>
  );
};

export default RsTextInput;

const generateStyles = (theme: Theme, style: RsTextStyle, isFocused: boolean) =>
  StyleSheet.create({
    container: {
      width: '100%',
      minHeight: 44,
      paddingHorizontal: 12,
      paddingVertical: Platform.OS === 'android' ? 4 : 10,
      borderWidth: 1,
      borderRadius: 10,
      borderColor: isFocused ? theme.Borders.inputActive : theme.Borders.input,
      backgroundColor: theme.Background.input,
      flexDirection: 'row',
      alignItems: 'center',
    },
    input: {
      flex: 1,
      padding: 0,
      margin: 0,
      color: style.color || theme.Text.inputText || theme.Text.text,
      fontSize: style.fontSize,
      textAlign: style.textAlign,
      fontFamily: `Cairo-${style.fontWeight}-Tight`,
      textTransform: style.textTransform,
      includeFontPadding: false,
      textAlignVertical: 'center',
    },
  });
