import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { useVuelidate } from '@vuelidate/core';

import ModelloLiberatoriaService from '@/entities/modello-liberatoria/modello-liberatoria.service';
import UtenteAppService from '@/entities/utente-app/utente-app.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { type ILiberatoria, Liberatoria } from '@/shared/model/liberatoria.model';
import { type IModelloLiberatoria } from '@/shared/model/modello-liberatoria.model';
import { type IUtenteApp } from '@/shared/model/utente-app.model';

import LiberatoriaService from './liberatoria.service';

export default defineComponent({
  name: 'LiberatoriaUpdate',
  setup() {
    const liberatoriaService = inject('liberatoriaService', () => new LiberatoriaService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const liberatoria: Ref<ILiberatoria> = ref(new Liberatoria());

    const utenteAppService = inject('utenteAppService', () => new UtenteAppService());

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

    const modelloLiberatoriaService = inject('modelloLiberatoriaService', () => new ModelloLiberatoriaService());

    const modelloLiberatorias: Ref<IModelloLiberatoria[]> = ref([]);
    const isSaving = ref(false);
    const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'it'), true);

    const route = useRoute();
    const router = useRouter();

    const previousState = () => router.go(-1);

    const retrieveLiberatoria = async liberatoriaId => {
      try {
        const res = await liberatoriaService().find(liberatoriaId);
        res.accettata = new Date(res.accettata);
        liberatoria.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.liberatoriaId) {
      retrieveLiberatoria(route.params.liberatoriaId);
    }

    const initRelationships = () => {
      utenteAppService()
        .retrieve()
        .then(res => {
          utenteApps.value = res.data;
        });
      modelloLiberatoriaService()
        .retrieve()
        .then(res => {
          modelloLiberatorias.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      accettata: {},
      utente: {},
      modelloLiberatoria: {},
    };
    const v$ = useVuelidate(validationRules, liberatoria as any);
    v$.value.$validate();

    return {
      liberatoriaService,
      alertService,
      liberatoria,
      previousState,
      isSaving,
      currentLanguage,
      utenteApps,
      modelloLiberatorias,
      v$,
      ...useDateFormat({ entityRef: liberatoria }),
      t$,
    };
  },
  created(): void {},
  methods: {
    save(): void {
      this.isSaving = true;
      if (this.liberatoria.id) {
        this.liberatoriaService()
          .update(this.liberatoria)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showInfo(this.t$('smartbookingApp.liberatoria.updated', { param: param.id }));
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      } else {
        this.liberatoriaService()
          .create(this.liberatoria)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showSuccess(this.t$('smartbookingApp.liberatoria.created', { param: param.id }).toString());
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      }
    },
  },
});
