/* Dependencies */
import React, { useState, useEffect } from 'react'
import { StyleSheet, Text, View } from 'react-native'

/* Libraries */
import { exceptThis } from '@hproinformatica/functions'
import { TextInput, IconButton, useTheme, Surface } from 'react-native-paper'

/* Types */
type Props = {
	title: string
	color: string
}

const Color = ({ title, color }: Props) => {
	/* Styles */
	const { colors } = useTheme()
	const styles = StyleSheet.create({
		colorInput: {
			height: 50,
			marginRight: 10,
			width: 80
		},
		container: {
			backgroundColor: colors.background,
			borderRadius: 15,
			display: 'flex',
			elevation: 4,
			marginBottom: 20,
			padding: 10
		},
		title: {
			color: colors.text,
			fontSize: 20,
			fontWeight: 'bold',
			marginBottom: 5,
			marginLeft: 5
		}
	})

	/* States */
	const [red, setRed] = useState('')
	const [green, setGreen] = useState('')
	const [blue, setBlue] = useState('')
	const [hex, setHex] = useState('')
	const [col, setCol] = useState('')
	const [display, setDisplay] = useState('HEX')

	/* Functions */ // TODO
	function rgbToHex(r: number, g: number, b: number) {
		return '#' + ((1 << 24) + (r << 16) + (g << 8) + b)
			.toString(16)
			.slice(1)
	}

	function hexToRgb(hex: string) {
		let result = new RegExp(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i).exec(hex)
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		}
			:
			null
	}

	const handleRgbToHex = () => {
		setHex(rgbToHex(parseInt(red), parseInt(green), parseInt(blue)).replace('#', ''))
		setDisplay('HEX')
	}

	const handleHexToRgb = () => {

		let cAux = ''
		if (hex.length !== 6) {
			if (hex.length === 3) {
				cAux = `${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}`
			} else if (hex.length < 3) {
				cAux = `ffffff`
			} else if (hex.length > 3) {
				cAux = `${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}`
			}
		} else {
			cAux = hex
		}

		let xAux = hexToRgb(cAux)
		if (xAux) {
			setRed(xAux.r.toString())
			setGreen(xAux.g.toString())
			setBlue(xAux.b.toString())
		} else {
			setRed('0')
			setGreen('0')
			setBlue('0')
		}
		setDisplay('RGB')
	}

	/* Hooks */
	useEffect(() => {
		setHex(exceptThis(color, '#'))
		setCol(color)
	}, [])

	return (<>
		<Surface style={styles.container}>
			<Text style={styles.title}>
				{title}
			</Text>
			<View style={{ padding: 5, display: 'flex', flexDirection: 'row' }}>
				<Text style={{ color: colors.text, marginRight: 15 }}>
					{'Cor escolhida'}
				</Text>
				<View style={{ backgroundColor: col, borderRadius: 15, height: 40, flex: 1 }} />
			</View>
			<View style={{ display: 'flex', flexDirection: 'row' }}>
				{
					(display === 'RGB')
						? (<>
							<TextInput
								autoCompleteType={'off'}
								keyboardType={'numeric'}
								label={'R'}
								maxLength={3}
								mode={'flat'}
								onChangeText={(event) => {
									setRed(event)
									setCol(rgbToHex(parseInt(event), parseInt(green), parseInt(blue)))
								}}
								style={styles.colorInput}
								value={red} />
							<TextInput
								autoCompleteType={'off'}
								keyboardType={'numeric'}
								label={'G'}
								maxLength={3}
								mode={'flat'}
								onChangeText={(event) => {
									setGreen(event)
									setCol(rgbToHex(parseInt(red), parseInt(event), parseInt(blue)))
								}}
								style={styles.colorInput}
								value={green} />
							<TextInput
								autoCompleteType={'off'}
								keyboardType={'numeric'}
								label={'B'}
								maxLength={3}
								mode={'flat'}
								onChangeText={(event) => {
									setBlue(event)
									setCol(rgbToHex(parseInt(red), parseInt(green), parseInt(event)))
								}}
								style={styles.colorInput}
								value={blue} />
						</>)
						: (<>
							<TextInput
								autoCompleteType={'off'}
								label={'Hexadecimal (sem #)'}
								maxLength={6}
								mode={'flat'}
								onChangeText={(event) => {
									setHex(event)
									return (event.length === 3 || event.length === 6)
										? setCol(`#${event}`)
										: null
								}}
								style={{ height: 50, width: 260, marginRight: 10 }}
								value={hex} />
						</>)}
				<IconButton
					hasTVPreferredFocus={undefined} // TODO: Fix this
					tvParallaxProperties={undefined} // TODO: Fix this
					icon={(display === 'RGB')
						? 'alpha-h'
						: 'border-color'}
					onPress={() => (display === 'RGB')
						? handleRgbToHex()
						: handleHexToRgb()} />
			</View>
		</Surface>
	</>)
}

Color.displayName = 'Edit.Color'

export default Color
