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

/* Libraries */
import { dtoc } from '@hproinformatica/functions'
import DateTimePickerModal from 'react-native-modal-datetime-picker'
import Icon from 'react-native-vector-icons/FontAwesome'

/* Types */

interface DefaultProps {
	selectedDate: string
	setSelectedDate: React.Dispatch<React.SetStateAction<string>>
	visible: boolean
	setVisible: React.Dispatch<React.SetStateAction<boolean>>
	alwaysConfirm?: boolean
	iconColor?: string
	isDark?: boolean
	maximumDate?: Date
	minimumDate?: Date
	onConfirm?: (date: string) => void
	text?: string
	textColor?: string
	tip?: string
	useToday?: boolean
}

type Props = DefaultProps

const PickerDate = ({
	iconColor = '#00a099',
	isDark = false,
	maximumDate,
	minimumDate,
	onConfirm,
	alwaysConfirm = false,
	selectedDate,
	setSelectedDate,
	setVisible,
	textColor = '#00a099',
	text = '',
	tip = '(Clique para alterar)',
	useToday,
	visible
}: Props) => {
	let colorScheme = useColorScheme()

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

	return (
		<TouchableOpacity
			onPress={toggleVisible}
			style={styles.container}>
			<View style={styles.view}>
				<Icon
					color={iconColor}
					name={'calendar'}
					size={26} />
				<Text style={{ ...styles.text, color: textColor }}>
					{`${text}${selectedDate} ${selectedDate && tip}`}
				</Text>
			</View>
			<DateTimePickerModal
				date={
					useToday
						? new Date()
						: new Date(
							[
								selectedDate.substring(3, 5),
								selectedDate.substring(0, 2),
								selectedDate.substring(6, 10)
							].join('/')
						)
				}
				maximumDate={maximumDate}
				minimumDate={minimumDate}
				headerTextIOS={'Selecione a data'}
				isDarkModeEnabled={colorScheme === 'dark' || isDark}
				isVisible={visible}
				mode={'date'}
				display={Platform.OS === 'ios' ? 'inline' : 'default'} //don't forget to add this line on IOS
				onCancel={toggleVisible}
				onConfirm={(date) => {
					toggleVisible()

					let dDat = new Date()
					if (selectedDate) {
						dDat = new Date([
							selectedDate.substring(3, 5),
							selectedDate.substring(0, 2),
							selectedDate.substring(6, 10)
						].join('/'))
					}

					if (alwaysConfirm || (dtoc(dDat) !== dtoc(date))) {
						setSelectedDate?.(dtoc(date))
						onConfirm?.(dtoc(date))
					}
				}}
			/>
		</TouchableOpacity>
	)
}

PickerDate.displayName = 'Picker.Date'

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

export default PickerDate
