<template>
	<div class="container-global-index">
		<v-tabs v-model="bookingData.tab" class="mb-3">
			<template v-for="t in bookingData.tabs">
				<v-tab
					:disabled="!!t.request.loading"
					:to="{ query: { tab: t.id } }"
					:value="t.id"
					@click="bookingData.tabSet(t.id)"
				>
					<span>{{ t.name }}</span>
					<span v-if="t.request.response.data.pagination.total">
						({{ t.request.response.data.pagination.total }})
					</span>
				</v-tab>
			</template>
		</v-tabs>

		<v-window v-model="bookingData.tab">
			<template v-for="t in bookingData.tabs">
				<v-window-item :value="t.id">
					<app-loading
						v-if="
							t.request.loading &&
							t.request.response.data.entities == 0
						"
						:text="`Loading ${t.name} <br />Bookings.`"
					/>
					<app-empty
						v-if="
							!t.request.loading &&
							t.request.response.data.entities == 0
						"
						:text="`No ${t.name} Bookings.`"
					/>

					<template
						v-for="(item, ii) in t.request.response.data.entities"
					>
						<div v-if="ii > 0" class="border-t mx-n6"></div>
						<v-row class="my-0">
							<v-col cols="12" lg="3" md="3" sm="3">
								<router-link
									:to="`/${guestPanelPath}/booking/${item.id}`"
								>
									<img
										v-if="
											bookingData.propertyImageUrl(item)
										"
										:src="
											bookingData.propertyImageUrl(item)
										"
										alt=""
										class="rounded"
										style="
											width: 100%;
											height: 150px;
											object-fit: cover;
										"
									/>
									<v-skeleton-loader
										v-if="
											!bookingData.propertyImageUrl(item)
										"
										class="mb-2 rounded-md overflow-hidden"
										type="image"
									/>
								</router-link>
								<div class="text-center">
									<div
										class="text-primary font-weight-bold text-uppercase"
									>
										{{ item?.property?.properties?.name }}
									</div>
									<v-rating
										:model-value="item?.property?.properties?.property_rating || 0"
										color="primary"
										readonly
										size="25"
									></v-rating>
								</div>
							</v-col>
							<v-col cols="12" lg="9" md="9" sm="9">
								<v-defaults-provider
									:defaults="{
										global: {
											hideDetails: true,
											variant: 'plain',
											readonly: true,
										},
									}"
								>
									<v-row class="ma-0">
										<v-col cols="3">
											<v-text-field
												:model-value="
													dateFormatDate(
														item.checkin_date,
													)
												"
												label="Arrival"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="
													dateFormatDate(
														item.checkout_date,
													)
												"
												label="Departure"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="item.checkin_hour"
												label="Check-in"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="
													item.checkout_hour
												"
												label="Check-out"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="item.days"
												label="Nights"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="
													item.booking_guests
														? item.booking_guests
																.adults
														: 0
												"
												label="Adults"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="
													item.booking_guests
														? item.booking_guests
																.children
														: 0
												"
												label="Children"
											></v-text-field>
										</v-col>
										<v-col cols="3">
											<v-text-field
												:model-value="
													bookingData.paymentStatus(
														item,
													)
												"
												label="Payment status"
											></v-text-field>
										</v-col>
										<v-col
											class="d-flex justify-content-end"
											cols="12"
										>
											<v-spacer/>
											<v-btn
												:to="`/${guestPanelPath}/booking/${item.id}`"
												class="bg-primary mr-2"
												:readonly="false"
											>
												View Details
											</v-btn>
											<v-btn
												:to="`/${guestPanelPath}/booking/${item.id}/messages`"
												class="bg-primary"
												:readonly="false"
											>
												Messages
											</v-btn>
										</v-col>
									</v-row>
								</v-defaults-provider>
							</v-col>
						</v-row>
					</template>
				</v-window-item>
			</template>
		</v-window>
	</div>
</template>

<script setup>
const {onMounted, reactive, watch} = Vue;

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

const props = defineProps({
	auth: {
		type: Object,
		default: () => ({}),
	},
});

const guestPanelPath = window.env?.sas_guest_panel_route;

const responseDefault = {
	success: false,
	data: {
		pagination: {
			total: 0,
		},
		entities: [],
	},
};

const route = VueRouter.useRoute();
const bookingData = reactive({
	tabSet(id) {
		bookingData.tabs.map((tab) => {
			if (tab.id != id) return;
			bookingData.tab = id;
			tab.request.submit();
		});
	},
	initHandler() {
		bookingData.tabSet(route.query.tab || "approved");
	},
	tab: false,
	tabs: [
		{
			id: "approved",
			name: "Approved",
			request: useAxios({
				method: "get",
				url: "/booking",
				params: {
					origin: "guest",
					per_page: 9999,
					criteria: {
						filter_group: [
							{
								filters: [
									{
										field: "checkout_date",
										value: window
											.$moment()
											.utc()
											.format("YYYY-MM-DD"),
										condition_type: "gteq",
										condition: "where",
									},
									{
										field: "status",
										value: "complete active pending",
										condition_type: "in",
										condition: "whereIn",
									},
								],
								orders: [
									{
										field: "created_at",
										direction: "desc",
									},
								],
							},
						],
					},
				},
				response: responseDefault,
			}),
		},
		{
			id: "past",
			name: "Past",
			request: useAxios({
				method: "get",
				url: "/booking",
				params: {
					origin: "guest",
					per_page: 9999,
					criteria: {
						filter_group: [
							{
								filters: [
									{
										field: "checkout_date",
										value: window
											.$moment()
											.utc()
											.format("YYYY-MM-DD"),
										condition_type: "lt",
										condition: "where",
									},
								],
								orders: [
									{
										field: "created_at",
										direction: "asc",
									},
								],
							},
						],
					},
				},
				response: responseDefault,
			}),
		},
		{
			id: "cancelled",
			name: "Cancelled",
			request: useAxios({
				method: "get",
				url: "/booking",
				params: {
					origin: "guest",
					per_page: 9999,
					criteria: {
						filter_group: [
							{
								filters: [
									{
										field: "status",
										value: "refunded canceled cancelled",
										condition_type: "in",
										condition: "whereIn",
									},
								],
								orders: [
									{
										field: "created_at",
										direction: "desc",
									},
								],
							},
						],
					},
				},
				response: responseDefault,
			}),
		},
		{
			id: "approval",
			name: "My Booking Requests",
			request: useAxios({
				type: "get",
				url: "/vendor/property_booking_approvals",
				headers: {SearchAndStayApiToken: "null"},
				params: {
					origin: "guest",
					per_page: 9999,
					criteria: {
						filter_group: [
							{
								filters: [
									{
										field: "booking_approval_status",
										condition_type: "in",
										condition: "whereIn",
										value: "pending",
									},
									{
										field: "booking_approval",
										condition_type: "eq",
										condition: "where",
										value: "1",
									},
									{
										field: "is_approval_request",
										condition_type: "eq",
										condition: "where",
										value: "1",
									},
								],
							},
						],
					},
				},
				response: responseDefault,
			}),
		},
	],
	propertyImageUrl(entity) {
		if (entity.property.property_images[0]) {
			return entity.property.property_images[0]["full_path"];
		}
		return null;
	},
	paymentStatus(entity) {
		switch (entity.booking_payments?.status || "") {
			case "complete":
				return "Complete";
				break;
			case "paid":
				return "Paid";
				break;
			case "partial_payment":
				return "Partial Paid";
				break;
			case "pending":
				return "Pending";
				break;
			case "refunded":
				return "Refunded";
				break;
			case "requires_action":
				return "Requires Action";
				break;
			case "canceled":
				return "Canceled";
				break;
		}
	},
});

watch([route], ([routeNew]) => {
	bookingData.initHandler();
});

onMounted(() => {
	setTimeout(() => {
		bookingData.initHandler();
	}, 10);
});

const dateFormatDate = (date) => {
	return dateFormat(date);
};
</script>
