<script setup lang="ts">
import "@/assets/form.css";
import "@/assets/toast.css";

import RestaurantsMap from "../components/RestaurantsMap.vue";
import { ref } from "vue";
import CreateRestaurantModal from "../components/CreateRestaurantModal.vue";

const errorMessage = ref<string>();
const successMessage = ref<string>();

const createRestaurantModal = ref<typeof CreateRestaurantModal>();

function onMapClicked(latlng) {
  createRestaurantModal.value?.setRestaurantPosition(latlng);
  createRestaurantModal.value?.show();
}

function resetToast() {
  successMessage.value = undefined;
  errorMessage.value = undefined;
}

function onRestaurantCreationSucceeded(message: string) {
  successMessage.value = message;
  errorMessage.value = undefined;
  createRestaurantModal.value?.hide();
  setTimeout(resetToast, 5000);
}

function onRestaurantCreationFailed(message: string) {
  successMessage.value = undefined;
  errorMessage.value = message;
  createRestaurantModal.value?.hide();
  setTimeout(resetToast, 5000);
}
</script>

<template>
  <div class="toast toast-top toast-end z-[10000]">
    <Transition name="toast-fade">
      <div v-if="errorMessage" class="alert alert-error">
        <span>{{ errorMessage }}</span>
      </div>
      <div v-else-if="successMessage" class="alert alert-success">
        <span>{{ successMessage }}</span>
      </div>
    </Transition>
  </div>

  <RestaurantsMap @clicked="onMapClicked" />

  <CreateRestaurantModal
    class="z-[10000]"
    @succeeded="onRestaurantCreationSucceeded"
    @failed="onRestaurantCreationFailed"
    ref="createRestaurantModal"
  />
</template>
