<template>
	<div :class="guestClasses">
		<div
			v-for="(item, key) in items"
			:key="key"
			class="py-2 order-1 order-md-1"
		>
			<Item
				v-if="item.length"
				:key="`guest-${key}`"
				v-model="innerValue[item[keyIndex]]"
				:can-add="!maxReached"
				:item="item"
				:max-pets="maxPets"
				:min-value="minValues[item[keyIndex]]"
				@update:modelValue="change"
			>
				<v-row
					v-if="isInfant(item) && innerValue[item[keyIndex]] > 0"
					class="mx-0"
				>
					<v-col
						v-for="(infant, index) in parseInt(
							innerValue[item[keyIndex]],
						)"
						:key="index"
						class="p-0"
						cols="12"
					>
						<v-text-field
							v-model="innerValue.infantAges[infant - 1]"
							:error-messages="
								getErrors(innerValue.infantAges[infant - 1])
							"
							:max="2"
							:min="0"
							class="p-0"
							hide-details="auto"
							placeholder="Age"
							:label="`infant age ${index + 1}`"
							size="sm"
							type="number"
							@keydown="
								$event.key === '-'
									? $event.preventDefault()
									: null
							"
						/>
					</v-col>
				</v-row>
			</Item>
		</div>

		<template v-if="petsProperties">
			<div>
				<v-checkbox
					v-model="innerValue['pets']"
					class="h5 guest-pets-checkbox"
					name="pets-checkbox"
					size="lg"
				>
					<template v-slot:label>
						Pets
						<small><i>Only properties that allow pets</i></small>
					</template>
				</v-checkbox>
			</div>
		</template>
	</div>
</template>

<script>
export default {
	components: {
		Item: Vue.defineAsyncComponent(() =>
			loadModule(
				window.SAS_URL + "/src/components/guests/Item.vue",
				options,
			),
		),
	},
	props: {
		guestClasses: {
			type: String,
			default: "",
		},
		keyIndex: {
			type: Number,
			default: 0,
		},
		petsProperties: {
			type: Boolean,
			default: false,
		},
		property: {
			type: Object,
			default: () => ({}),
		},
		modelValue: {
			type: Object,
			default: () => ({}),
		},
	},
	data() {
		return {
			innerValue: {},
			minValues: {},
			maxPets: -1,
			maxValues: -1,
			maxReached: false,
			items: [
				["adult", "adults", "(18+)"],
				["child", "children", "(3 - 17)"],
				["infant", "infants", "(0 - 2)"],
			],
		};
	},
	computed: {
		isPetFriendly() {
			return !!this.property.property_amenities.find((el) =>
				[159].includes(el.id),
			);
		},
	},
	watch: {
		property: {
			immediate: true,
			handler(value) {
				this.maxPets = parseInt(
					value.property_basic_informations?.property_restrictions
						?.maximum_pets,
				);
				this.maxValues =
					parseInt(
						value.property_basic_informations?.property_restrictions
							?.maximum_guests,
					) || -1;
			},
		},
		items: {
			deep: true,
			immediate: true,
			handler() {
				this.createDefault();
				this.getMinValues();
			},
		},
		innerValue: {
			deep: true,
			handler(value) {
				this.$emit("update:modelValue", value);
				if (!value.infantAges) return;

				const requiredNumbers = ["0", "1", "2", ""];
				const hasAllRequiredNumbers = value.infantAges?.every((num) =>
					requiredNumbers.includes(num),
				);
				this.$emit("validationGuest", !hasAllRequiredNumbers);

				if (value.infants === 0) {
					this.$emit("validationGuest", false);
				}
			},
		},
		modelValue: {
			immediate: true,
			deep: true,
			handler(value) {
				this.innerValue = value;
			},
		},
	},
	mounted() {
		let current_total = 0;
		this.items.forEach((el) => {
			if (["infantAges", "pets", "pet"].includes(el[this.keyIndex]))
				return 0;
			current_total += this.innerValue[el[this.keyIndex]];
		});

		if (this.isPetFriendly) {
			this.items.push(["pet", "pets", ""]);
		}

		this.maxReached = current_total === this.maxValues;
	},
	methods: {
		change() {
			if (this.innerValue["infants"] === 0) {
				this.innerValue["infantAges"] = [];
			}
			if (this.innerValue["infants"] && !this.innerValue["infantAges"])
				this.innerValue["infantAges"] = [];
			if (
				this.innerValue["infants"] >
				this.innerValue["infantAges"]?.length
			)
				this.innerValue["infantAges"].push(0);
			else if (
				this.innerValue["infants"] <
				this.innerValue["infantAges"]?.length
			)
				this.innerValue["infantAges"].pop();

			let current_total = 0;
			this.items.forEach((el) => {
				if (["infantAges", "pets", "pet"].includes(el[this.keyIndex]))
					return 0;
				current_total += this.innerValue[el[this.keyIndex]];
			});
			this.maxReached = current_total === this.maxValues;
			this.$emit("change", this.innerValue);
		},
		createDefault() {
			this.items.forEach((el) => {
				if (this.innerValue && !this.innerValue[el[this.keyIndex]])
					this.innerValue[el[this.keyIndex]] =
						this.minValues[el[this.keyIndex]] || 0;
			});
		},
		getMinValues() {
			this.minValues = this.items.reduce((total, current) => {
				total[current[this.keyIndex]] = 0;
				if (current[this.keyIndex] === "adult") {
					total[current[this.keyIndex]] = 1;
				}
				return total;
			}, {});
		},
		isInfant(item) {
			return ["infant", "infants"].includes(item[0]);
		},
		getErrors(value) {
			if (value < 0 || value > 2 || value === undefined || value === "") {
				return "Value expected between 0 and 2";
			}
		},
	},
};
</script>
