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

/* Libraries */
import DateTimePickerModal from 'react-native-modal-datetime-picker'
import Icon from 'react-native-vector-icons/FontAwesome'

/* Types */
type Props = {
	selectedTime: string
	setSelectedTime: React.Dispatch<React.SetStateAction<string>>
	visible: boolean
	setVisible: React.Dispatch<React.SetStateAction<boolean>>
	text?: string
	tip?: string
	useNow?: boolean
}

const PickerTime = ({
	visible,
	setVisible,
	selectedTime,
	setSelectedTime,
	text = '',
	tip = '(Clique para alterar)',
	useNow
}: Props) => {
	let colorScheme = useColorScheme()

	const formTime = (date = new Date()) => {
		let hours = date.getHours().toString()
		hours = (hours.length < 2) ? `0${hours}` : hours

		let minutes = date.getMinutes().toString()
		minutes = (minutes.length < 2) ? `0${minutes}` : minutes

		return `${hours}:${minutes}`
	}

	useEffect(() => {
		if (!selectedTime) {
			setSelectedTime(formTime())
		}
	}, [])

	const toggleVisible = () => {
		setVisible((value) => !value)
	}

	return (<>
		<TouchableOpacity
			onPress={toggleVisible}
			style={styles.container}>
			<View style={styles.view}>
				<Icon
					color={'#00a099'}
					name={'clock-o'}
					size={26} />
				<Text style={styles.text}>
					{`${text}${selectedTime} ${selectedTime && tip}`}
				</Text>
			</View>
			<DateTimePickerModal
				date={useNow
					? new Date()
					: new Date(`2021-01-01T${selectedTime}:00.000Z`)}
				headerTextIOS={'Selecione a hora'}
				isDarkModeEnabled={colorScheme === 'dark'}
				isVisible={visible}
				mode={'time'}
				onCancel={toggleVisible}
				onConfirm={(date) => {
					toggleVisible()
					setSelectedTime(formTime(date))
				}} />
		</TouchableOpacity>
	</>)
}

PickerTime.displayName = 'Picker.Time'

const styles = StyleSheet.create({
	container: {
		alignItems: 'center',
		flex: 1,
		flexDirection: 'row',
		height: 40,
		justifyContent: 'center'
	},
	view: {
		flexDirection: 'row'
	},
	text: {
		color: '#00a099',
		fontSize: 20,
		fontWeight: 'bold',
		marginLeft: 15
	}
})

export default PickerTime
