<template>
	<v-defaults-provider
		:defaults="{
			VTextField: {
				hideDetails: true,
				variant: 'plain',
				readonly: true,
			},
		}"
	>
		<app-loading v-if="!booking.response && booking.loading"/>
		<app-empty
			v-if="!booking.response && !booking.loading"
			text="Booking not found"
		/>

		<template v-if="booking.response">
			<!-- <div class="pa-3 mt-n3 mx-n3 border-b font-weight-bold text-uppercase">
			  #{{ booking.response.data.id }} - Booking Details
			</div>
			<div class="my-3"></div> -->

			<div id="print-ref" ref="printRef">
				<v-row>
					<v-col cols="12" md="12">
						<v-table class="border">
							<template #default>
								<colgroup>
									<col width="*"/>
									<col width="200px"/>
								</colgroup>
								<tbody>
								<tr>
									<th class="property-name" colspan="2">
										{{
											booking.response.data.property
												.properties.name
										}}
									</th>
								</tr>
								<tr>
									<th>Check-in</th>
									<td class="align-right">
										{{
											dateFormatData(
												`${booking.response.data.checkin_date} ${booking.response.data.checkin_hour}:00`,
												"DD/MM/YYYY - HH:mm",
											)
										}}
									</td>
								</tr>
								<tr>
									<th>Check-out</th>
									<td class="align-right">
										{{
											dateFormatData(
												`${booking.response.data.checkout_date} ${booking.response.data.checkout_hour}:00`,
												"DD/MM/YYYY - HH:mm",
											)
										}}
									</td>
								</tr>
								<tr>
									<th>Payment Status</th>
									<template
										v-if="
												booking.response.data
													.booking_payments.status ===
												'partial_payment'
											"
									>
										<td class="align-right">
											Partial Paid
										</td>
									</template>
									<template v-else>
										<td class="align-right">
											{{
												booking.statusText(
													booking.response.data
														.status,
												)
											}}
										</td>
									</template>
								</tr>
								</tbody>
							</template>
						</v-table>

						<div class="my-3"></div>

						<template
							v-if="
								booking.response.data.booking_payments.deposit
							"
						>
							<div class="text-h6">Security Deposit</div>
							<div class="my-3"></div>
							<div>
								{{
									moneyDate(
										booking.response.data.deposit,
										booking.response.data.booking_payments
											.currency.code,
									)
								}}
							</div>
							<div class="my-3"></div>
						</template>
					</v-col>

					<v-col cols="12" md="6">
						<template v-if="booking.paymentsCancellationPolicies">
							<div class="text-h6">Cancellation Policy</div>
							<div class="my-3"></div>

							<v-table class="border">
								<template #default>
									<tbody>
									<tr>
										<td
											v-if="
													booking
														.paymentsCancellationPolicies
														.fee > 0
												"
										>
											Cancellation allowed - Fee:
											<strong>{{
													moneyDate(
														booking
															.paymentsCancellationPolicies
															.fee,
														booking.response.data
															.booking_payments
															.currency.code,
													)
												}}</strong>
										</td>
									</tr>
									<tr
										v-for="(r, i) in booking
												.paymentsCancellationPolicies
												.rules"
									>
										<td class="py-2">
											If cancellation is requested
											<strong
											>{{
													r.days_range
												}}
												days</strong
											>
											before check-in,
											<strong
											>{{
													r.percent_back || 0
												}}%</strong
											>
											back of paid amount.
										</td>
									</tr>
									</tbody>
								</template>
							</v-table>
							<div class="my-3"></div>
						</template>

						<template
							v-if="
								booking.response.data.booking_payments.deposit
							"
						>
							<div class="text-h6">Security Deposit</div>
							<div class="my-3"></div>
							<div>
								{{
									moneyDate(
										booking.response.data.deposit,
										booking.response.data.booking_payments
											.currency.code,
									)
								}}
							</div>
							<div class="my-3"></div>
						</template>

						<template v-if="booking.propertyConfigurationRules">
							<div class="text-h6">House Rules</div>
							<div class="my-3"></div>

							<v-table class="border">
								<template #default>
									<tbody>
									<tr
										v-for="(
												r, i
											) in booking.propertyConfigurationRules"
									>
										<td>
											<i>{{ r.name }}</i>
										</td>
									</tr>
									</tbody>
								</template>
							</v-table>
							<div class="my-3"></div>
						</template>
					</v-col>

					<v-col cols="12" md="6">
						<div class="text-h6">Booking Summary</div>
						<div class="my-3"></div>

						<v-table class="border">
							<template #default>
								<colgroup>
									<col width="*"/>
									<col width="200px"/>
								</colgroup>
								<tbody>
								<tr>
									<th>
										{{ booking.response.data.days }}
										{{ booking.response.data.days === 1 ? "night" : "nights" }}
									</th>
									<td class="align-right">
										{{
											moneyDate(total_period, booking.response.data.booking_payments.currency.code)
										}}
									</td>
								</tr>

								<tr v-if="extras.total_extras">
									<td>
										<i>Extras</i>
									</td>
									<td class="align-right">
										{{
											moneyDate(extras.total_extras, booking.response.data.booking_payments.currency.code)
										}}
									</td>
								</tr>

								<tr>
									<td>
										<i>Non-refundable booking fee</i>
									</td>
									<td class="align-right">
										{{
											moneyDate(booking_fee, booking.response.data.booking_payments.currency.code)
										}}
									</td>
								</tr>

								<tr>
									<td>
										<i>Non-refundable card transaction fee</i>
									</td>
									<td class="align-right">
										{{
											moneyDate(operator_fee, booking.response.data.booking_payments.currency.code)
										}}
									</td>
								</tr>

								<tr>
									<td>
										<strong>TOTAL:</strong>
									</td>
									<td class="align-right">
										<v-tooltip class="mr-2">
											<template #activator="{ props }">
												<v-icon
													icon="mdi-help-circle"
													class="mr-1"
													v-bind="props"
												/>
											</template>

											All fees and extras included
										</v-tooltip>

										<strong>
											{{
												moneyDate(total_period_fees, booking.response.data.booking_payments.currency.code)
											}}
										</strong>
									</td>
								</tr>
								</tbody>
							</template>
						</v-table>

						<div class="my-3"></div>
						<div class="text-h6">Partial Payment</div>
						<div class="my-3"></div>

						<v-table class="border">
							<template #default>
								<tbody>
								<template v-if="booking.paymentParcelsNotBond">
									<template v-for="(loop, index) in booking.paymentParcelsNotBond">
										<tr>
											<td>Due {{ dateFormatData(`${loop.date}`, "DD/MM/YYYY") }}</td>

											<td class="text-capitalize">
												<template v-if="loop.status === 'paid'">
													{{ loop.status }}
												</template>
												<template
													v-else-if="loop.status === 'pending' && !isInterHome && loop.id === nextInstalment && isBookingApproved && isBeforeCheckin">
													<v-btn
														:loading="loadingConfirmPayment[index]"
														color="primary"
														@click="havePaymentIntent(loop) ? confirmPayment(loop, index) : makeInstalment(loop)"
													>
														{{ havePaymentIntent(loop) ? "Confirm" : "Pay Now" }}
													</v-btn>
												</template>
											</td>

											<td class="align-right">
												{{
													moneyDate(loop.value, booking.response.data.booking_payments.currency.code)
												}}
											</td>
										</tr>
									</template>

									<template v-if="booking.response.data.booking_refunds?.length > 0">
										<tr class="text-danger" style="font-size: medium">
											<td>Refunded at
												{{
													dateFormatData(`${booking.response.data.booking_refunds[0].created_at}`, "DD/MM/YYYY")
												}}
											</td>

											<td></td>

											<td class="align-right">
												- {{
													moneyDate(sumValueRefunded(booking.response.data.booking_refunds), booking.response.data.booking_payments.currency.code)
												}}
											</td>
										</tr>
									</template>

									<tr v-if="!booking.paymentParcelsBond">
										<td>
											<strong>TOTAL PAID:</strong>
										</td>
										<td></td>
										<td class="align-right">
											<strong>
												{{
													moneyDate(booking.response.data.booking_payments.total_paid, booking.response.data.booking_payments.currency.code)
												}}
											</strong>
										</td>
									</tr>
								</template>
								</tbody>
							</template>
						</v-table>

						<div
							v-if="booking.paymentParcelsBond"
							class="my-3"
						></div>
						<div v-if="booking.paymentParcelsBond" class="text-h6">
							Security Bond
						</div>
						<div
							v-if="booking.paymentParcelsBond"
							class="my-3"
						></div>

						<v-table class="border">
							<template #default>
								<tbody>
								<template v-if="booking.paymentParcelsBond">
									<template v-for="(bond, index) in booking.paymentParcelsBond">
										<tr>
											<td>
												Due
												{{ dateFormatData(`${bond.date}`, "DD/MM/YYYY") }}
											</td>

											<td>
												<template
													v-if="bond.status === 'pending' && !isInterHome && bond.id === nextInstalment && isBookingApproved && isBeforeCheckin"
												>
													<v-btn
														:loading="loadingConfirmPayment[index]"
														color="primary"
														@click="havePaymentIntent(bond) ? confirmPayment(bond, index) : makeInstalment(bond)"
													>
														{{
															havePaymentIntent(bond) ? "Confirm" : "Pay Now"
														}}
													</v-btn>
												</template>

												<template v-else>
													{{
														bond.status === 'not_processed' ? 'Not Processed' : bond.status
													}}
												</template>
											</td>

											<td class="align-right">
												{{
													moneyDate(bond.value, booking.response.data.booking_payments.currency.code)
												}}
											</td>
										</tr>
									</template>
									<template
										v-for="bond in booking.paymentParcelsBond"
									>
										<tr
											class="flex-row justify-space-between"
										>
											<td>
												Held
												{{
													dateFormatData(`${bond.held_date}`, "DD/MM/YYYY")
												}}
											</td>
											<td></td>
											<td class="align-right">
												{{
													moneyDate(bond.value, booking.response.data.booking_payments.currency.code)
												}}
											</td>
										</tr>
									</template>
									<tr>
										<td>
											<strong>TOTAL PAID:</strong>
										</td>
										<td></td>
										<td class="align-right">
											<strong>
												{{
													moneyDate(booking.response.data.booking_payments.total_paid, booking.response.data.booking_payments.currency.code)
												}}
											</strong>
										</td>
									</tr>
								</template>
								</tbody>
							</template>
						</v-table>

						<v-alert
							v-if="successPayment"
							class="mt-5"
							closable
							text="Payment successfully"
							type="success"
						/>
						<v-alert
							v-if="returnPaymentIntent.show"
							:text="returnPaymentIntent.message"
							:type="returnPaymentIntent.type"
							class="mt-5"
							closable
						/>

						<div class="my-3"></div>
						<!-- <pre>{{ booking.summary }}</pre> -->
					</v-col>
				</v-row>
			</div>

			<!-- Cancel dialog -->
			<v-dialog v-model="cancel.modal" width="600">
				<v-card title="Cancelation">
					<v-card-text style="max-height: 60vh; overflow: auto">
						<v-textarea
							v-model="cancel.data.bookings.summary_cancellation"
							auto-grow
							label="Summary Cancellation"
						></v-textarea>
					</v-card-text>
					<v-card-actions>
						<v-btn @click="cancel.modal = false"> Cancel</v-btn>
						<v-spacer></v-spacer>
						<v-btn
							:loading="cancel.loading"
							color="primary"
							@click="cancel.submit()"
						>
							Proceed cancel
						</v-btn>
					</v-card-actions>
				</v-card>
			</v-dialog>

			<!-- Instalment Payment -->
			<v-dialog v-model="booking.instalment.modal" width="700">
				<v-card title="Instalment Payment">
					<vendorShowLeanFull
						v-model="paymentBooking.payment_method"
						:paymentData="paymentBooking"
						class="mb-4"
						label="Select card"
						@update:newCard="
							paymentBooking.save_card = $event ? 1 : null
						"
					/>

					<div
						v-if="instalment.origin === 'bond'"
						class="elevation-2 rounded-lg"
					>
						<v-card-title class="border-b text-capitalize">
							Bond
						</v-card-title>
						<v-row align="start" align-content="start" class="ma-3">
							<v-col cols="12"
							><strong>Value:</strong>
								{{ instalment.payNow.value }}
							</v-col>
							<v-col cols="12"
							><strong>Due Date:</strong>
								{{
									dateFormatData(
										instalment.payNow.held_date,
										"DD/MM/YYYY",
									)
								}}
							</v-col>
							<v-col class="text-capitalize" cols="12"
							><strong>Status:</strong>
								{{ instalment.payNow.status }}
							</v-col>
						</v-row>
					</div>

					<v-alert
						v-if="errorPayment.show"
						:text="extractErrorMessage"
						class="my-5"
						closable
						type="error"
					/>

					<v-card-actions
						class="flex-row justify-content-between w-100"
					>
						<v-btn @click="booking.instalment.modal = false">
							Cancel
						</v-btn>
						<v-spacer></v-spacer>
							<!-- :disabled="
								Object.values(
									paymentBooking.payment_method ?? {},
								)?.length === 0
							" -->
						<v-btn
							:loading="booking.instalment.loading"
							color="primary"
							@click="payment()"
						>
							Pay Now
						</v-btn>
					</v-card-actions>
				</v-card>
			</v-dialog>

			<div class="mx-n3 my-3 border-t"></div>

			<v-row class="my-0">
				<!--				<v-col cols="12" lg="6" md="6" sm="6">-->
				<!--					<v-btn color="primary" @click="contentPrint()">Print</v-btn>-->
				<!--				</v-col>-->

				<!--				<v-spacer></v-spacer>-->

				<v-col
					class="container-buttons"
					cols="12"
					style="gap: 15px"
				>
					<v-btn :to="guestPage">Back</v-btn>
					<v-btn
						v-if="!['refunded'].includes(booking.response.data.status)"
						:loading="cancel.loading"
						color="error"
						@click="cancel.modal = true"
					>
						Cancel Booking
					</v-btn>
				</v-col>
			</v-row>
		</template>
	</v-defaults-provider>
</template>

<script setup>
const vendorShowLeanFull = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/vendor/ShowLeanFull.vue`, options),
);

const AppLoading = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/AppLoading.vue`, options),
);

const AppEmpty = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/AppEmpty.vue`, options),
);

// import {usePaperizer} from "paperizer";
const {computed, reactive, ref} = Vue;
const {useRoute} = VueRouter;

const guestPage = `/${window.env.sas_guest_panel_route}`;
const paymentBooking = ref({payment_method: {}, save_card: null});
const instalment = ref({payNow: {}, origin: ""});
const errorPayment = ref({show: false, message: ""});
const returnPaymentIntent = ref({show: false, message: "", type: "success"});
const successPayment = ref(false);
const loadingConfirmPayment = ref([false]);
const stripeData = reactive({card: {instance: false}, stripe: false});
const storeStripe = useStripeStore()
const { paymentMethod, cardValidation } = Pinia.storeToRefs(storeStripe)
const route = useRoute();
const props = defineProps({
	auth: {
		type: Object,
		default: () => ({}),
	},
	route: {
		type: Object,
		default: () => ({}),
	},
});

const extractErrorMessage = computed(() => {
	const message = errorPayment.value.message;
	if (!message || typeof message !== "object") {
		return message;
	}

	let errorMessage = "";

	Object.keys(message).forEach((key) => {
		if (Array.isArray(message[key])) {
			errorMessage += message[key].join(", ") + " ";
		} else {
			errorMessage += message[key] + " ";
		}
	});

	return errorMessage.trim();
});

const isInterHome = computed(
	() => booking.response.data.integration === "interhome",
);

const nextInstalment = computed(() => {
	let _parcels = booking.response.data?.booking_payments
		?.booking_payment_parcels
		? booking.response.data.booking_payments?.booking_payment_parcels?.filter(
			(bpp, i) => bpp.type != "bond" && bpp.status == "pending",
		)
		: "";
	let _bond = booking.response.data?.booking_payments?.booking_payment_parcels
		? booking.response.data.booking_payments?.booking_payment_parcels?.filter(
			(bpp, i) => bpp.type == "bond",
		)
		: "";
	if (_parcels?.length) {
		return _parcels[0].id;
	} else if (_bond?.length > 0) {
		return _bond[0].id;
	}

	return null;
});

const isBookingApproved = computed(() => {
	if (booking.response.data.is_approval_request)
		return (
			booking.response.data.booking_approval_status > 0 ||
			booking.response.data.booking_approval_status === "approved"
		);

	return true;
});

const isBeforeCheckin = computed(() => {
	return $moment().isSameOrBefore(
		$moment(booking.response.data.checkin_date),
		"day",
	);
});

const capitalize = (text) =>
	text.replace(/(^\w{1})|(\s+\w{1})/g, (letter) => letter.toUpperCase());

// const contentPrint = () => {
// 	const {paperize} = usePaperizer("print-ref", {
// 		styles: ["https://cdn.jsdelivr.net/npm/vuetify@3.3.6/dist/vuetify.min.css"],
// 	});
// 	paperize();
// };

const booking = useAxios({
	method: "get",
	url: `/booking/${route.params.id}`,
	params: {origin: "guest"},
	autoSubmit: true,

	statusText(code) {
		return capitalize(code.split("_").join(" "));
	},

	paymentsCancellationPolicies: computed(() => {
		if (!booking.response) return false;
		if (!booking.response.data.booking_payments.cancellation_policies)
			return false;
		if (
			booking.response.data.booking_payments.cancellation_policies
				.allowed !== 1
		)
			return false;

		const policies = {
			...booking.response.data.booking_payments.cancellation_policies,
			rules: booking.response.data.booking_payments.cancellation_policies.rules.filter(
				(item) => {
					return item.active;
				},
			),
		};

		if (policies.rules?.length === 0) return false;
		return policies;
	}),

	propertyConfigurationRules: computed(() => {
		if (!booking.response) return false;
		if (!booking.response.data.property.property_configurations)
			return false;
		if (
			booking.response.data.property.property_configurations.rules
				?.length === 0
		)
			return false;

		const rules =
			booking.response.data.property.property_configurations.rules.filter(
				(rule) => {
					return rule.active === 1;
				},
			);

		if (rules?.length === 0) return;
		return rules;
	}),

	taxes: computed(() => {
		if (!booking.response) return [];
		let items = booking.response.data.taxes.filter((item) => {
			return (
				item.refundable === false &&
				!item.tax_type.includes("operator_fee")
			);
		});

		if (items?.length === 0) return false;
		return items;
	}),

	paymentParcelsBond: computed(() => {
		if (!booking.response) return [];
		let items =
			booking.response.data.booking_payments.booking_payment_parcels.filter(
				(item) => {
					return item.type === "bond";
				},
			);
		if (items?.length === 0) return false;
		return items;
	}),

	paymentParcelsBondTotal: computed(() => {
		if (!booking.response) return [];
		return booking.paymentParcelsBond?.length === 0
			? 0
			: booking.paymentParcelsBond.reduce((total, item) => {
				return total + item.value;
			}, 0);
	}),

	paymentParcelsNotBond: computed(() => {
		if (!booking.response) return [];
		let items =
			booking.response.data.booking_payments.booking_payment_parcels.filter(
				(item) => {
					return item.type !== "bond";
				},
			);
		if (items?.length === 0) return false;
		return items;
	}),

	instalment: useAxios({
		modal: false,
	}),
});

const booking_fee = computed(() => {
	let _taxes = booking.response.data.taxes

	if (_taxes) {
		return parseFloat(
			_taxes?.find((tax) => tax.tax_type === 'booking_fee')?.value
		)
	}

});

const extras = computed(() => {
	let total_extras = 0
	let extras = []
	booking.response.data.taxes?.filter(
		(tx) => tx.tax_operation === 'extra_fees' && tx.value > 0
	)
		.map((ex) => {
			total_extras += parseFloat(ex.value)
			if (
				ex.tax_type === 'linen' ||
				ex.tax_type === 'extra_linen'
			) {

				extras.push(
					//to do, bring vendor currency
					`Linen: ${parseFloat(ex.value)}`
				)
			}
			if (
				ex.tax_type === 'extra_cleaning_fee' ||
				ex.tax_type === 'block_cleaning_cost_fee'
			) {
				extras.push(
					`Cleaning: ${parseFloat(ex.value)}`
				)
			}
		})

	return {
		total_extras,
		extras
	}
});

const operator_fee = computed(() => {
	return booking.response.data.booking_payments ? parseFloat(booking.response.data.booking_payments.operator_fee) : parseFloat(booking.response.data.operator_fee)

});

const total_period_fees = computed(() => {
	return booking.response.data.booking_payments
		? parseFloat(booking.response.data.booking_payments.base_sub_total)
		: parseFloat(booking.response.data.base_sub_total)

});

const total_period = computed(() => {
	try {
		return booking.response.data.booking_payments
			? parseFloat(booking.response.data.booking_payments.base_total) + parseFloat(booking.response.data.booking_payments.sas_fee)
			: parseFloat(booking.response.data.base_total)
	} catch (e) {
		console.error(e)
		return 0
	}
});

const cancel = useAxios({
	modal: false,
	method:
		booking?.response?.data?.integration === "interhome"
			? "delete"
			: "post",
	url:
		booking?.response?.data?.integration === "interhome"
			? `/bookings/interhome/cancel/${route.params.id}`
			: `/booking/refund_payment/${route.params.id}`,
	data: {
		origin: "guest",
		canceled_by: "guest",
		bookings: {
			summary_cancellation: "",
		},
	},
	onSuccess(r) {
		booking.response.data = r.data.data
		successPayment.value = false

		returnPaymentIntent.value = {show: true, message: 'Canceled successfully', type: 'success'}

		cancel.modal = false
	},
	onError() {
		successPayment.value = false
		returnPaymentIntent.value = {show: true, message: 'Error canceling', type: 'error'}

		cancel.modal = false
	}
});

const payment = async (id) => {
	booking.instalment.loading = true;

	if (storeStripe.valueRadio === "new-card") {
		await storeStripe.createPaymentMethod(true);
	}

	if (storeStripe.cardValidation.type === "error") {
		booking.instalment.loading = false;
		return;
	}

	// if (Object.values(paymentBooking.payment_method ?? {}).length === 0) {
	// 	booking.instalment.loading = false;

	// 	return;
	// }
	
	let _url = `/booking/do_payment/${booking.response.data.id}`;
	let payload = {
		bookings: {
			booking_payment_parcel_id: instalment.value.payNow.id,
			installment: 1,
		},
		payment_method: {
			...paymentMethod.value || paymentBooking.value.payment_method,
			id: paymentMethod.value.stripe_payment_method_id || paymentBooking.value.payment_method.stripe_payment_method_id,
		},
	};

	if (instalment.value.origin === "quote") {
		_url = `/booking/store`;

		payload = {
			financial: {
				customer: {
					origin: "guest",
					customer_type: "guest",
				},
			},
			bookings: {
				...booking.response.data,
				property_id: booking.response.data.property.properties.id,
				quote_id: booking.response.data.id,
				adults: booking.response.data.booking_guests.adults,
				childs: booking.response.data.booking_guests.children,
				payment_method_code: "rental-united",
				checkin_date: booking.response.data.checkin_date,
				checkout_date: booking.response.data.checkout_date,
			},
			payment_method: {
				...paymentMethod.value || paymentBooking.value.payment_method,
				id: paymentMethod.value.stripe_payment_method_id || paymentBooking.value.payment_method.stripe_payment_method_id,
			},
		};
	}

	await axios
		.post(_url, payload)
		.then(async (r) => {
			successPayment.value = true;
			booking.instalment.modal = false;
			const returnStripe = await stripe3DS(r.data.data);
			booking.response.data = r.data.data;
			if (returnStripe) {
				returnPaymentIntent.value = {
					show: true,
					message: returnStripe.message,
					type: "error",
				};
				return;
			}
			this.stripeData.card.instance.clear()
			paymentMethod.value = {}
		})
		.catch((e) => {
			if(e.response.data.message) {
				errorPayment.value.show = true;
				errorPayment.value.message = e.response.data.message;
			}
		})
		.finally(() => {
			booking.instalment.loading = false;
		});
};

const makeInstalment = (payNow) => {
	const origin = booking.response.data.type ?? "booking";
	instalment.value = {payNow, origin};
	booking.instalment.modal = true;
};

const stripeKey = useAxios({
	url: "/vendor/stripe_keys?",
	method: "get",
	autoSubmit: true,
	onSuccess() {
		stripeData.stripe = Stripe(stripeKey.response.data.key);
	},
});

const stripe3DS = async (booking) => {
	const parcelIntent = booking.booking_payments.booking_payment_parcels
		.find((p) => p.status === "pending" && p.payment_intent?.length)
		?.payment_intent.find((p) => p.status === "requires_action");
	if (parcelIntent) {
		const {stripe} = stripeData;
		const elements = stripe.elements();
		stripeData.card.instance = elements.create("card");

		const intentValues =
			parcelIntent.payment_intent_log &&
			parcelIntent.payment_intent_log[0];
		const {paymentIntent, error} = await stripe.confirmCardPayment(
			intentValues.client_secret,
			{payment_method: intentValues.payment_method},
		);
		if (paymentIntent) {
			booking.response.data.booking_payments.booking_payment_parcels.forEach(
				(p) => {
					if (p.id === instalment.value.payNow.id) {
						p.status = "paid";
					}
				},
			);
		}

		return error;
	}
};

const confirmPayment = async (parcel, index) => {
	try {
		loadingConfirmPayment.value[index] = true;

		const intentValues = parcel.payment_intent.find(
			(pi) => pi.status === "requires_action",
		)?.payment_intent_log[0];

		if (intentValues) {
			const {stripe} = stripeData;
			const elements = stripe.elements();
			stripeData.card.instance = elements.create("card");

			const {paymentIntent, error} =
				await stripeData.stripe.confirmCardPayment(
					intentValues.client_secret,
					{
						payment_method: intentValues.payment_method,
					},
				);

			returnPaymentIntent.value = {show: false, message: "", type: ""};
			if (paymentIntent) {
				booking.response.data.booking_payments.booking_payment_parcels.forEach(
					(p) => {
						if (p.id === parcel.id) {
							p.status = "paid";
						}
					},
				);
				returnPaymentIntent.value = {
					show: true,
					message: "Payment confirmed",
					type: "success",
				};
			} else if (error) {
				returnPaymentIntent.value = {
					show: true,
					message: error.message,
					type: "error",
				};
			}
		}
	} catch (e) {
		console.error(e);
	} finally {
		loadingConfirmPayment.value[index] = false;
	}
};

const havePaymentIntent = (parcel) => {
	return (
		parcel.payment_intent.length &&
		parcel.payment_intent.find((pi) => pi.status === "requires_action")
	);
};

const moneyDate = (moneyBooking, currency) => {
	return money(moneyBooking, currency);
};

const dateFormatData = (date, format) => {
	return dateFormat(date, format);
};

const sumValueRefunded = (bookingRefunds) => {
	return bookingRefunds.reduce((total, refund) => {
		return total + parseFloat(refund.value_refunded);
	}, 0);
}
</script>

<style scoped>
.property-name {
	text-transform: capitalize;
	font-size: 1.2rem;
}

.align-right {
	text-align: right;
}

.container-buttons {
	display: flex;
	justify-content: flex-end;

	@media screen and (max-width: 480px) {
		justify-content: space-between;
	}
}
</style>
