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 ConfermaService from '@/entities/conferma/conferma.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { type IConferma } from '@/shared/model/conferma.model';
import { TipoCanaleNotifica } from '@/shared/model/enumerations/tipo-canale-notifica.model';
import { TipoEventoNotifica } from '@/shared/model/enumerations/tipo-evento-notifica.model';
import { type INotifica, Notifica } from '@/shared/model/notifica.model';

import NotificaService from './notifica.service';

export default defineComponent({
  name: 'NotificaUpdate',
  setup() {
    const notificaService = inject('notificaService', () => new NotificaService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const notifica: Ref<INotifica> = ref(new Notifica());

    const confermaService = inject('confermaService', () => new ConfermaService());

    const confermas: Ref<IConferma[]> = ref([]);
    const tipoCanaleNotificaValues: Ref<string[]> = ref(Object.keys(TipoCanaleNotifica));
    const tipoEventoNotificaValues: Ref<string[]> = ref(Object.keys(TipoEventoNotifica));
    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 retrieveNotifica = async notificaId => {
      try {
        const res = await notificaService().find(notificaId);
        res.inviataAt = new Date(res.inviataAt);
        res.createdAt = new Date(res.createdAt);
        notifica.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.notificaId) {
      retrieveNotifica(route.params.notificaId);
    }

    const initRelationships = () => {
      confermaService()
        .retrieve()
        .then(res => {
          confermas.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      tipoCanale: {},
      tipoEvento: {},
      messaggio: {},
      inviata: {},
      inviataAt: {},
      errore: {},
      createdAt: {},
      conferma: {},
    };
    const v$ = useVuelidate(validationRules, notifica as any);
    v$.value.$validate();

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