import moment from "moment";
import React, { Component } from "react";
import { Modal, View, TouchableOpacity, StyleSheet } from "react-native";
import { Calendar } from "react-native-calendars";
import { StatusBarHeight } from "../helper";
import { FontAwesome } from "./Icon";
import {
	hexToRGBAstring,
	COLOUR_RED,
	TEXT_DARK,
	COLOUR_GRAPEFRUIT,
} from "../colours";

class CalendarPopup extends Component {
	constructor(props) {
		super(props);

		this.state = {};
	}

	onDayPress = (date) => {
		const { onSelect } = this.props;
		if (!onSelect) return;

		// console.log('onDayPress', date);
		onSelect(date.timestamp);
	};

	renderClose() {
		const { onClose } = this.props;
		return (
			<TouchableOpacity
				style={styles.menuIconContainer}
				onPress={onClose}
				activeOpacity={0.6}
			>
				<FontAwesome name="x" style={styles.menuIcon} />
			</TouchableOpacity>
		);
	}

	render() {
		const {
			visible,
			animationType,
			onClose,
			backgroundStyle,
			selectedDate,
			minDate,
			maxDate,
			enabledDates,
			selectedColor,
			enabledColor,
			disabledColor,
			theme,
		} = this.props;

		const initialDate = (selectedDate ? moment(selectedDate) : moment()).format(
			"YYYY-MM-DD",
		);
		const min = minDate ? moment(minDate).format("YYYY-MM-DD") : undefined;
		const max = maxDate ? moment(maxDate).format("YYYY-MM-DD") : undefined;
		const dateMarkings = {};
		(enabledDates || []).forEach((date) => {
			const { day, enabled } = date;
			const key = moment(day).format("YYYY-MM-DD");
			dateMarkings[key] = {
				enabled,
				disableTouchEvent: !enabled,
				customStyles: {
					text: {
						color: enabled
							? enabledColor || TEXT_DARK
							: disabledColor || COLOUR_RED,
					},
				},
			};
		});
		// console.log('CalendarPopup - enabled', JSON.stringify(dateMarkings, null, 2));
		return (
			<Modal
				transparent
				visible={visible || false}
				animationType={animationType || "fade"}
				onRequestClose={onClose}
			>
				<View
					style={[
						styles.popup,
						backgroundStyle || { backgroundColor: hexToRGBAstring("#fff", 1) },
					]}
				>
					<Calendar
						initialDate={initialDate}
						minDate={min}
						maxDate={max}
						markingType={"custom"}
						markedDates={{
							...dateMarkings,
							[initialDate]: {
								selected: true,
								selectedColor: selectedColor || COLOUR_GRAPEFRUIT,
							},
						}}
						onDayPress={this.onDayPress}
						theme={theme}
					/>
				</View>
				{this.renderClose()}
			</Modal>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		backgroundColor: "#000",
	},
	popup: {
		flex: 1,
		justifyContent: "center",
	},
	menuIconContainer: {
		position: "absolute",
		top: StatusBarHeight(0),
		right: 0,
		width: 55,
		height: 55,
		zIndex: 3,
	},
	menuIcon: {
		fontSize: 30,
		padding: 15,
		width: 65,
		textAlign: "center",
		color: "#000",
		zIndex: 3,
	},
});

export { CalendarPopup };
