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 ILiberatoria } from '@/shared/model/liberatoria.model';

import LiberatoriaService from './liberatoria.service';

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

    const liberatorias: Ref<ILiberatoria[]> = ref([]);

    const isFetching = ref(false);

    const clear = () => {};

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

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

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

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

    return {
      liberatorias,
      handleSyncList,
      isFetching,
      retrieveLiberatorias,
      clear,
      ...dateFormat,
      removeId,
      removeEntity,
      prepareRemove,
      closeDialog,
      removeLiberatoria,
      t$,
    };
  },
});
