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 useDataUtils from '@/shared/data/data-utils.service';
import { type IModelloLiberatoria } from '@/shared/model/modello-liberatoria.model';

import ModelloLiberatoriaService from './modello-liberatoria.service';

export default defineComponent({
  name: 'ModelloLiberatoria',
  setup() {
    const { t: t$ } = useI18n();
    const dateFormat = useDateFormat();
    const dataUtils = useDataUtils();
    const modelloLiberatoriaService = inject('modelloLiberatoriaService', () => new ModelloLiberatoriaService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const modelloLiberatorias: Ref<IModelloLiberatoria[]> = ref([]);

    const isFetching = ref(false);

    const clear = () => {};

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

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

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

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

    return {
      modelloLiberatorias,
      handleSyncList,
      isFetching,
      retrieveModelloLiberatorias,
      clear,
      ...dateFormat,
      removeId,
      removeEntity,
      prepareRemove,
      closeDialog,
      removeModelloLiberatoria,
      t$,
      ...dataUtils,
    };
  },
});
