import { type Ref, defineComponent, inject, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';

import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat } from '@/shared/composables';
import { type IMessaggio } from '@/shared/model/messaggio.model';

import MessaggioService from './messaggio.service';

export default defineComponent({
  name: 'Messaggio',
  setup() {
    const { t: t$ } = useI18n();
    const dateFormat = useDateFormat();
    const messaggioService = inject('messaggioService', () => new MessaggioService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const messaggios: Ref<IMessaggio[]> = ref([]);

    const isFetching = ref(false);

    const clear = () => {};

    const retrieveMessaggios = async () => {
      isFetching.value = true;
      try {
        const res = await messaggioService().retrieve();
        messaggios.value = res.data;
      } catch (err) {
        alertService.showHttpError(err.response);
      } finally {
        isFetching.value = false;
      }
    };

    const handleSyncList = () => {
      retrieveMessaggios();
    };

    onMounted(async () => {
      await retrieveMessaggios();
    });

    const removeId: Ref<number> = ref(null);
    const removeEntity = ref<any>(null);
    const prepareRemove = (instance: IMessaggio) => {
      removeId.value = instance.id;
      removeEntity.value.show();
    };
    const closeDialog = () => {
      removeEntity.value.hide();
    };
    const removeMessaggio = async () => {
      try {
        await messaggioService().delete(removeId.value);
        const message = t$('smartbookingApp.messaggio.deleted', { param: removeId.value }).toString();
        alertService.showInfo(message, { variant: 'danger' });
        removeId.value = null;
        retrieveMessaggios();
        closeDialog();
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    return {
      messaggios,
      handleSyncList,
      isFetching,
      retrieveMessaggios,
      clear,
      ...dateFormat,
      removeId,
      removeEntity,
      prepareRemove,
      closeDialog,
      removeMessaggio,
      t$,
    };
  },
});
