import {Image, StyleSheet, Text, TextInput, TextInputProps, ImageSourcePropType,TouchableOpacity, View} from 'react-native'
import React from 'react'
import {Utils} from 'tuya-panel-kit'
import res from '../res'
import ThemeType from '../config/themeType'

const cx = Utils.RatioUtils.convertX
const { withTheme } = Utils.ThemeUtils

interface TextFieldProps extends TextInputProps {
  theme?: ThemeType
  showError?: boolean
  errorText?: string
  tipIcon?: ImageSourcePropType
  tipColor?: string
  editable?: boolean
}

const TextField = (props: TextFieldProps) => {
  const icon = props.tipIcon || res.ic_warning_amber
  const color = props.tipColor || props.theme?.global.warning
  const editable = props.editable ?? !props.editable

  const styles = StyleSheet.create({
    topTip: {
      marginTop: cx(5),
      fontSize: cx(12),
      marginStart: cx(13),
      color: props.theme?.global.secondFontColor,
      fontFamily: 'helvetica_neue_lt_std_bd',
    },
    textInputGroup: {
      flexDirection: 'row',
      borderRadius: cx(4),
      backgroundColor: props.theme?.textInput.background,
      alignItems: 'center',
    },
    textInput: {
      flex: 1,
      height: cx(44),
      marginStart: cx(16),
      marginEnd: cx(6),
      fontSize: cx(16),
      color: props.theme?.textInput.fontColor,
      fontFamily: 'helvetica_neue_lt_std_roman',
    },
    iconTouchable: {
      marginEnd: cx(18),
      padding: cx(4),
    },
    icon: {
      width: cx(16),
      height: cx(16),
    },
    line: {
      height: 1,
      position: 'absolute',
      start: cx(4),
      end: cx(4),
      bottom: 0,
      backgroundColor: props.theme?.textInput.line,
    },
    errorContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      marginStart: cx(13),
    },
  })
  return (
    <View style={props.style}>
      <Text style={[styles.topTip, { opacity: (!!props.value) ? 1 : 0 }]}>{props.placeholder}</Text>
      <View style={styles.textInputGroup}>
        <TextInput{...props} style={styles.textInput} />
        {!!props.value && editable &&
            <TouchableOpacity
                style={styles.iconTouchable}
                onPress={() => {
                  props.onChangeText && props.onChangeText('')
                }}>
                <Image source={{ uri: res.ic_cancel }} style={styles.icon} />
            </TouchableOpacity>
        }
        <View style={styles.line} />
      </View>
      <View style={[styles.errorContainer, { opacity: !!(props.showError) ? 1 : 0 }]}>
        <Image source={icon} style={[styles.icon, { tintColor: color }]} />
        <Text
          style={{ marginLeft: cx(5), color: color }}
        >{props.errorText}</Text>
      </View>
    </View>
  )
}

export default withTheme(TextField)
