<template>
  <span
    v-if="data.working_ref_status === 'to_review'"
    class="badge bg-danger address-details-button-warning"
    >L'adresse de référence a été modifiée</span
  >
  <a
    v-if="data.loading === false"
    @click.prevent="clickOrOpen"
    class="btn btn-sm address-details-button"
    title="Plus de détails"
  >
    <span class="fa fa-map-o"></span>
  </a>
  <span v-if="data.loading" class="fa fa-spin fa-spinner"></span>
  <AddressModal
    :address="data.working_address"
    @update-address="onUpdateAddress"
    ref="address_modal"
  ></AddressModal>
</template>

<script lang="ts" setup>
import { Address, AddressRefStatus } from "../../../types";
import { onMounted, reactive, ref } from "vue";
import { getAddressById } from "../../../lib/api/address";
import AddressModal from "./AddressModal.vue";

export interface AddressModalContentProps {
  address_id: number;
  address_ref_status: AddressRefStatus;
}

interface AddressModalData {
  loading: boolean;
  working_address: Address | null;
  working_ref_status: AddressRefStatus | null;
}

const data: AddressModalData = reactive({
  loading: false,
  working_address: null,
  working_ref_status: null,
} as AddressModalData);

const props = defineProps<AddressModalContentProps>();

const emit = defineEmits<(e: "update-address", value: Address) => void>();

const address_modal = ref<InstanceType<typeof AddressModal> | null>(null);

onMounted(() => {
  data.working_ref_status = props.address_ref_status;
});

async function clickOrOpen(): Promise<void> {
  if (data.working_address === null) {
    data.loading = true;
    data.working_address = await getAddressById(props.address_id);
    data.working_ref_status = data.working_address.refStatus;
    data.loading = false;
  }

  // open the modal
  address_modal.value?.open();
}

const onUpdateAddress = (address: Address): void => {
  data.working_address = address;
  data.working_ref_status = address.refStatus;
  emit("update-address", address);
};
</script>

<style scoped lang="scss">
.address-details-button-warning {
  display: inline-block;
  margin-right: 0.3rem;
}
</style>
