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

import { useAlertService } from '@/shared/alert/alert.service';
import { type IUtenteApp } from '@/shared/model/utente-app.model';

import UtenteAppService from './utente-app.service';

export default defineComponent({
  name: 'UtenteApp',
  setup() {
    const { t: t$ } = useI18n();
    const utenteAppService = inject('utenteAppService', () => new UtenteAppService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const utenteApps: Ref<IUtenteApp[]> = ref([]);

    const isFetching = ref(false);

    const clear = () => {};

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

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

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

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

    return {
      utenteApps,
      handleSyncList,
      isFetching,
      retrieveUtenteApps,
      clear,
      removeId,
      removeEntity,
      prepareRemove,
      closeDialog,
      removeUtenteApp,
      t$,
    };
  },
});
