<template>
	<form class="saswp-theme-home-search" @submit.prevent="submit">
		<input
			v-model="url.params.initial_date"
			name="initial_date"
			type="hidden"
		/>
		<input
			v-model="url.params.final_date"
			name="final_date"
			type="hidden"
		/>
		<input v-model="url.params.guests" name="guests" type="hidden" />
		<input v-model="url.params.childs" name="childs" type="hidden" />
		<input v-model="url.params.pets" name="pets" type="hidden" />

		<v-container class="bg-white pa-0">
			<v-row
				align="center"
				:class="{ 'justify-content-between': props.hideButtonBookNow }"
				no-gutters
			>
        <v-col class="col-mobile-text-center">
          <!-- checkin -->
          <v-menu
            v-model="menu.initial_date"
            :close-on-content-click="false"
            offset="22px"
          >
            <template #activator="data">
              <v-col
                class="py-6 cursor-pointer"
                :class="{
                  'px-0 text-center': props.hideButtonBookNow,
                  'px-5': !props.hideButtonBookNow,
                }"
                v-bind="data.props"
              >
                <div class="f-poppins mb-3 f-16px f-fw-600">
                  Check-in
                </div>
                <span
                  class="f-poppins f-fw-500"
                  :class="
                    props.hideButtonBookNow
                      ? 'f-16px'
                      : 'f-20px'
                  "
                >
                  {{
                    url.params.initial_date
                      ? dateFormat(
                          url.params.initial_date,
                          "DD/MM/YYYY"
                        )
                      : "__/__/____"
                  }}
                </span>
              </v-col>
            </template>

            <v-card
              class="py-1 px-4"
              :width="isMobile ? '100%' : '750px'"
            >
              <template #title>
                <div class="w-100 text-end">
                  <v-icon
                    icon="mdi-close"
                    size="20px"
                    @click="menu.initial_date = false"
                  />
                </div>
              </template>

              <Calendar
                ref="calendar"
                v-model="url.params"
                :dateParams="{
                  from: url.params.initial_date,
                  to: url.params.final_date,
                }"
                :property="property"
                controls
                no-period-check
                picker
                single
                @select:to="(v) => selectDateToAndCloseModal(v)"
                @update:modelValue="(value) => updateDates(value)"
              />
            </v-card>
          </v-menu>
        </v-col>
        <v-col class="col-mobile-text-center">
          <!-- checkout -->
          <v-menu
            v-model="menu.final_date"
            :close-on-content-click="false"
            offset="22px"
          >
            <template #activator="data">
              <v-col
                class="py-6 cursor-pointer"
                :class="{
                  'px-0 text-center': props.hideButtonBookNow,
                  'px-5': !props.hideButtonBookNow,
                }"
                v-bind="data.props"
              >
                <div class="f-poppins mb-3 f-16px f-fw-600">
                  Check-out
                </div>
                <span
                  class="f-poppins f-fw-500"
                  :class="
                    props.hideButtonBookNow
                      ? 'f-16px'
                      : 'f-20px'
                  "
                >
                  {{
                    url.params.final_date
                      ? dateFormat(
                          url.params.final_date,
                          "DD/MM/YYYY"
                        )
                      : "__/__/____"
                  }}
                </span>
              </v-col>
            </template>

            <v-card
              class="py-1 px-4"
              :width="isMobile ? '100%' : '750px'"
            >
              <template #title>
                <div class="w-100 text-end">
                  <v-icon
                    icon="mdi-close"
                    size="20px"
                    @click="menu.final_date = false"
                  />
                </div>
              </template>

              <Calendar
                ref="calendar"
                v-model="url.params"
                :dateParams="{
                  from: url.params.initial_date,
                  to: url.params.final_date,
                }"
                :property="property"
                controls
                no-period-check
                picker
                single
                @select:to="(v) => selectDateToAndCloseModal(v)"
                @update:modelValue="(value) => updateDates(value)"
              />
            </v-card>
          </v-menu>
        </v-col>
        <v-col class="col-mobile-text-center">
          <!-- guests -->
          <v-menu
            v-model="menu.guests"
            :close-on-content-click="false"
            offset="22px"
          >
            <template #activator="data">
              <v-col
                class="py-6 px-5 d-flex cursor-pointer justify-content-center"
                :class="{
                  'px-0 text-center': props.hideButtonBookNow,
                  'px-5': !props.hideButtonBookNow,
                }"
                cols="12"
                :sm="props.hideButtonBookNow ? '4' : '2'"
                v-bind="data.props"
              >
                <div class="text-center">
                  <div class="f-poppins f-16px f-fw-600" style="margin-bottom: 1.3rem;">
                    Guests
                  </div>
                  <div
                    class="f-poppins f-fw-500 mb-1"
                    :class="
                      props.hideButtonBookNow
                        ? 'f-16px'
                        : 'f-30px'
                    "
                  >
                    {{ menu.guestsTotal }}
                  </div>
                </div>

                <div v-if="url.params.pets" class="ml-2">
                  <div class="f-poppins mb-3 f-16px f-fw-600">
                    Pets
                  </div>
                  <div
                    class="f-poppins f-fw-500"
                    :class="
                      props.hideButtonBookNow
                        ? 'f-16px'
                        : 'f-30px'
                    "
                  >
                    {{ url.params.pets }}
                  </div>
                </div>
              </v-col>
            </template>

            <v-defaults-provider
              :defaults="{
                VTextField: {
                  variant: 'outlined',
                },
              }"
            >
              <v-sheet
                class="pa-3 d-flex flex-column"
                elevation="0"
                rounded="0"
                style="gap: 15px; max-width: 320px"
              >
                <div class="w-100 text-end">
                  <v-icon
                    icon="mdi-close"
                    size="20px"
                    @click="menu.guests = false"
                  />
                </div>

                <Guests
                  v-model="url.params"
                  :key-index="1"
                  :property="property"
                  @validationGuest="
                    (v) => (menu.validationGuest = v)
                  "
                  @update:model-value="menu.guestsCalculate()"
                />

                <div class="text-right">
                  <v-btn
                    :disabled="menu.validationGuest"
                    @click="closeMenuGuests()"
                  >
                    Ok
                  </v-btn>
                </div>
              </v-sheet>
            </v-defaults-provider>
          </v-menu>
        </v-col>
			</v-row>

			<v-progress-linear indeterminate v-if="loadingQuotes" />

			<v-row
				align="center"
				no-gutters
				class="pa-6"
				v-if="
					Object.values(quotesBooking ?? {}).length &&
					!errorQuotes?.length
				"
			>
				<sas-booking-summary
					class="w-100"
					:property="props.property"
					:quotes="quotesBooking"
				/>

				<v-divider />
				<v-btn
					:disabled="
						!url.params.final_date ||
						menu.validationGuest ||
						loadingQuotes
					"
					block
					color="secondary"
					elevation="0"
					rounded="0"
					size="large"
					type="submit"
				>
					Book now
				</v-btn>
			</v-row>

			<div>
				<v-alert
					v-if="errorQuotes?.length"
					class="my-3"
					style="border-radius: 10px"
					type="error"
					closable
					v-for="message in errorQuotes"
				>
					{{ message }}
				</v-alert>
			</div>

			<v-dialog
				v-model="bookingDialog"
				:width="step === 'login' && !isMobile ? '40%' : '90%'"
			>
				<v-card>
					<PropertyBooking
						v-if="bookingDialog"
						:property="property"
						:search="url.params"
						singleProperty
						@step="(v) => (step = v)"
					/>
					<v-card-actions class="border-t">
						<v-spacer />
						<v-btn @click="bookingDialog = false">Close</v-btn>
					</v-card-actions>
				</v-card>
			</v-dialog>
		</v-container>
	</form>
</template>

<script setup>
const { defineAsyncComponent, computed, ref, onBeforeMount, reactive } = Vue;

const sasBookingSummary = defineAsyncComponent(() =>
	loadModule(SAS_URL + "/src/components/booking/Summary.vue", options)
);

const Guests = defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/guests/List.vue`, options)
);
const PropertyBooking = defineAsyncComponent(() =>
	loadModule(`${SAS_URL}/src/components/property/Booking.vue`, options)
);

const Calendar = defineAsyncComponent(
	async () =>
		await loadModule(
			`${SAS_URL}/src/components/calendar/Calendar.vue`,
			options
		)
);

// const { useUrl } = app.config.globalProperties.useUrl;

// const calendar = ref(null);
const bookingDialog = ref(false);
const step = ref("");
const loadingQuotes = ref(false);
const quotesBooking = ref({});
const errorQuotes = ref(null);
const propertiesStore = usePropertiesStore();
const calendarStore = useCalendarStore();
const property = ref({});

const emit = defineEmits(["updateDates", "updateGuests", "closeMenuGuests"]);

const props = defineProps({
	args: { type: Object, default: () => ({}) },
	property: { type: Object, default: () => ({}) },
	hideButtonBookNow: { type: Boolean, default: false },
	blockedLoadProperty: { type: Boolean, default: false },
});

onBeforeMount(async () => {
	menu.guestsCalculate();
	if (props.blockedLoadProperty) {
		property.value = props.property;
		return;
	}
	await loadProperty();
});

const loadProperty = async () => {
	try {
		loadingQuotes.value = true;
		const { data } = await axios.get(
			`/guest/properties/${props.property.properties.id}/${props.property.properties.slug}`
		);

		property.value = useProperty(data.data);

		const criteria = serialize({
			filters: [
				{
					field: "published",
					value: 1,
					condition_type: "eq",
					condition: "where",
				},
			],
		});

		propertiesStore
			.getPropertySeasons({
				id: property.value.properties.id,
				criteria,
				per_page: 999,
			})
			.then((result) => {
				const key = property.value.properties.id;
				const value = result.data.data.entities;

				if (Array.isArray(value)) {
					calendarStore.seasonsPropertyMonth[key] = value;
				} else {
					calendarStore.seasonsPropertyMonth[key] = {
						...(calendarStore.seasonsPropertyMonth[key] ?? {}),
						...value,
					};
				}

				calendarStore.seasonsPropertyMonth = {
					...calendarStore.seasonsPropertyMonth,
				};
			});
	} catch (e) {
		console.error(e);
	} finally {
		loadingQuotes.value = false;
	}
};

// onMounted(async () => {
//   loading.value = true;
//   await store.setProperties();
//
//   const dateCalendar = calendar.value.getValidPeriod(moment().add(2, "d"));
//   url.params.initial_date = dateCalendar.dateFrom.format("YYYY-MM-DD");
//   url.params.final_date = dateCalendar.dateTo.format("YYYY-MM-DD");
//
//   loading.value = false;
// });

const isMobile = computed(() => {
	return window.screen.width <= 959;
});

const url = useUrl({
	params: {
		initial_date: undefined,
		final_date: undefined,
		adults: 2,
	},
});

const menu = reactive({
	initial_date: false,
	final_date: false,
	guests: false,
	guestsTotal: 0,
	validationGuest: false,
	// onSelected(date) {
	//   console.log(date)
	//   date = moment(date).format('YYYY-MM-DD');
	//
	//   if (!url.params.initial_date) {
	//     url.params.initial_date = date;
	//     url.params.final_date = null;
	//     this.initial_date = false;
	//     this.final_date = true;
	//   } else {
	//     url.params.final_date = date;
	//     this.initial_date = false;
	//     this.final_date = false;
	//   }
	// },
	guestsCalculate() {
		this.guestsTotal =
			Number(url.params.adults || 0) +
			Number(url.params.children || 0) +
			Number(url.params.infants || 0);
		emit("updateGuests", { guests: this.guestsTotal, ...url.params });
	},
});

const submit = () => {
	bookingDialog.value = true;
};

const updateDates = (v) => {
	if (Object.values(v ?? {}).length === 0) return;

	url.params.initial_date = v.from;
	url.params.final_date = v.to;

	if (v.from && v.to) {
		emit("updateDates", v);
	}
};

const selectDateToAndCloseModal = (v) => {
	if (v.date !== undefined) {
		url.params.final_date = v.date;
		loadQuoteBooking();

		menu.initial_date = false;
		menu.final_date = false;
	}
};

const closeMenuGuests = () => {
	menu.guests = false;
	loadQuoteBooking();
	emit("closeMenuGuests", url.params);
};

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

const loadQuoteBooking = async () => {
	try {
		if (loadingQuotes.value) return;

		loadingQuotes.value = true;
		errorQuotes.value = null;
		const quotes = {
			account_id: useUserStore().getUser?.account_id,
			checkin_date: url.params.initial_date,
			checkout_date: url.params.final_date,
			adults: url.params.adults || 2,
			children: url.params.children || 0,
			infantAges: url.params.infantAges || [],
			infants: url.params.infants || 0,
			pets: url.params.pets || 0,
			property_id: props.property.properties.id,
		};
		const { data } = await axios.post("/quotes/store", { quotes });
		quotesBooking.value = data.data;
	} catch (e) {
		errorQuotes.value = e.response.data.message;
		quotesBooking.value = {};
	} finally {
		loadingQuotes.value = false;
	}
};
</script>
