<template>
  <q-dialog ref="dlgRef" persistent>
    <q-card class="bg-dark text-grey-1 add-loc-card q-pa-sm">
      <q-toolbar>
        <q-avatar icon="mdi-map-marker" color="primary" text-color="white" />
        <q-toolbar-title>Add Location to Queue</q-toolbar-title>
      </q-toolbar>
      <q-card-section class="q-ml-lg">
        <div>Are you sure you want to set location to:</div>
        <div class="q-ml-md">
          <div class="relative-position">
            <div>
              <transition
                appear
                enter-active-class="animated fadeIn"
                leave-active-class="animated fadeOut"
              >
                <formatted-address :address="address" v-if="!loading" />
              </transition>
            </div>
            <q-inner-loading :showing="loading" />
          </div>

          <q-input
            class="q-mt-md"
            style="max-width: 150px"
            v-model.number="delay"
            filled
            @keyup.enter="onOkClick"
            label="Delay "
            type="number"
            suffix="seconds"
            color="grey-4"
            autofocus
          />
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="between">
        <div class="text-yellow">
          <q-checkbox
            class="cursor-pointer"
            v-model="isFavorite"
            checked-icon="mdi-star"
            unchecked-icon="mdi-star-outline"
            indeterminate-icon="mdi-help"
            color="yellow"
            @click="handleFavoriteClick"
            :label="favoriteName"
          >
            <q-tooltip>Favorite</q-tooltip>
          </q-checkbox>
        </div>
        <div>
          <q-btn flat label="OK" @click="onOkClick" />
          <q-btn flat label="Cancel" @click="onDialogCancel" />
        </div>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { useDialogPluginComponent } from 'quasar';
import { reverseGeocodeRateLimited } from 'functions/reverseGeocodeSocket';
import { ref, onMounted, computed } from 'vue';
import { useQuasar } from 'quasar';
import FormattedAddress from 'components/FormattedAddress.vue';
import EditFavoriteDialog from 'components/EditFavoriteDialog.vue';
import type { NominatimResponse } from 'components/models';

const props = defineProps({
  lat: { type: Number, required: true },
  lng: { type: Number, required: true },
});

const $q = useQuasar();
const loading = ref(true);
const delay = ref(300);

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef: dlgRef, onDialogOK, onDialogCancel } = useDialogPluginComponent();

const address = ref<NominatimResponse>();
const isFavorite = ref(false);
const favorite = ref();
const favoriteName = computed(() => favorite.value?.name ?? '');

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

onMounted(async () => {
  try {
    loading.value = true;
    const response = await reverseGeocodeRateLimited(props.lat, props.lng);
    console.log('reverse geocode response: ', response);
    address.value = response.address;
    if (response.favorite) {
      favorite.value = response.favorite;
    }
  } catch (error) {
    console.error('Error fetching reverse geocode:', error);
    throw error;
  } finally {
    await sleep(500);
    loading.value = false;
  }
});

function handleFavoriteClick() {
  if (!favorite.value) {
    favorite.value = {
      name: '',
      icon: '',
      category: '',
      latitude: props.lat,
      longitude: props.lng,
    };
  }
    $q.dialog({
      component: EditFavoriteDialog,
      componentProps: {
        lat: props.lat,
        lng: props.lng,
        fav: favorite.value,
      },
    })
    .onOk(({ data }) => {
        favorite.value = data;
    })
    .onCancel(() => {
      console.log('Dialog cancelled');
    })
    .onDismiss(() => {
      console.log('Dialog dismissed');
    });
}



function onOkClick() {
  onDialogOK({ delay: delay.value, address: address.value });
}
</script>
<style lang="sass" scoped>
.add-loc-card
  width: 100%
  max-width: 450px
</style>
