/* Dependencies */
import React, { forwardRef, useState } from 'react'
import type { KeyboardTypeOptions } from 'react-native'
import {
	StyleProp,
	StyleSheet,
	TextInput as ReactTextInput,
	TextStyle
} from 'react-native'

/* Libraries */
import { formatValue, toValue } from '@hproinformatica/functions'
import { TextInput, useTheme } from 'react-native-paper'

/* Types */
type Props = React.ComponentProps<typeof TextInput> & {
	decimal?: number
	disabled?: boolean
	field: string
	label: string
	onExit?: (value: string) => void
	setField: React.Dispatch<React.SetStateAction<string>>
	style?: StyleProp<TextStyle>
	type?: KeyboardTypeOptions
}

const EditNumber = forwardRef<ReactTextInput, Props>((props, forwardedRef) => {
	let {
		decimal = 2,
		disabled = false,
		field,
		label,
		onExit,
		setField,
		style,
		type = 'numeric',
		...rest
	} = props

	/* Styles */
	const { colors } = useTheme()
	const styles = StyleSheet.create({
		container: {
			flex: 1,
			margin: 5
		}
	})

	/* States */
	const [isFocused, setIsFocused] = useState(false)

	/* Events */
	function onBlur() {
		let value = ''
		if (!field) {
			value = formatValue(0, decimal)
			setField(value)
		} else {
			if (field.includes(',')) {
				if (isNaN(toValue(field))) {
					value = formatValue(0, decimal)
					setField(value)
				} else {
					value = formatValue(toValue(field), decimal)
					setField(value)
				}
			} else {
				if (isNaN(Number(field))) {
					value = formatValue(0, decimal)
					setField(value)
				} else {
					value = formatValue(Number(field), decimal)
					setField(value)
				}
			}
		}
		onExit?.(value)
	}

	function onFocus() {
		setIsFocused(true)
		if (toValue(field) === 0) {
			setField('')
		}
	}

	return (
		<TextInput
			disabled={disabled}
			keyboardType={type}
			label={label}
			mode={'flat'}
			onBlur={onBlur}
			onChangeText={(event) => setField(event)}
			onFocus={() => onFocus()}
			ref={forwardedRef}
			right={
				disabled ? null : (
					<TextInput.Icon
						hasTVPreferredFocus={undefined} // TODO: Fix this
						tvParallaxProperties={undefined} // TODO: Fix this
						name={'close'}
						size={28}
						color={isFocused ? colors.primary : 'rgb(100,100,100)'}
						onPress={() => setField('')}
					/>
				)
			}
			style={style ?? styles.container}
			value={field}
			{...rest}
		/>
	)
})

EditNumber.displayName = 'Edit.Number'

export default EditNumber
