<template>
	<booking-messages :booking-id="route.params.id" />
</template>

<script setup>
const BookingMessages = Vue.defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/ui/booking/Messages.vue`, options),
);

const { useRoute, useRouter } = VueRouter;
const { inject, ref } = Vue;

const route = useRoute();
const router = useRouter();

const guestPanelPath = inject("guestPanelPath");

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

const messageRef = ref(null);

const message = useAxios({
	method: "get",
	url: "/booking/booking_messages",
	// autoSubmit: true,
	params: {
		per_page: 9999,
		// page: 1,
		criteria: {
			filter_group: [
				{
					filters: [
						{
							condition: "where",
							field: "booking.id",
							condition_type: "eq",
							value: route.params.id,
						},
						{
							condition: "where",
							field: "message.type",
							condition_type: "eq",
							value: "message",
						},
					],
				},
			],
		},
	},
	response: {
		data: {
			entities: [],
			pagination: {
				total_pages: 0,
			},
		},
	},
	onSuccess(response) {
		response.data.data.entities.map((entity) => {
			if (route.params.id && route.query.id == entity.id) {
				message.setView(entity);
			}
		});
		bookingMessage.data.booking_messages.from_vendor_id =
			props.auth.response.data.id;
		bookingMessage.data.booking_messages.to_vendor_id =
			props.booking.response.data.vendor.id;
		setTimeout(() => {
			if (!messageRef.value) return;
			messageRef.value.scroll({
				top: messageRef.value.scrollHeight,
				behavior: "smooth",
			});
		}, 100);
	},
	view: false,
	setView(msg) {
		message.view = msg || false;
		router.push(
			guestPanelPath(
				msg
					? `/booking/${route.params.id}/messages?id=${msg.id}`
					: `/booking/${route.params.id}/messages`,
			),
		);
	},
	userImage(user) {
		return "??";
	},
});

// useIntervalFn(() => {
//   message.submit();
// }, 60 * 1000);

const bookingMessage = useAxios({
	method: "post",
	url: "/booking/booking_messages",
	data: {
		booking_messages: {
			booking_id: route.params.id,
			message: "",
			type: "message",
			from_origin: "guest",
			to_origin: "agency",
			from_vendor_id: null,
			to_vendor_id: 2,
			to_account_id: null,
		},
	},
	onSuccess() {
		message.submit();
		bookingMessage.data.booking_messages.message = "";
	},
});
</script>
