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 { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { type IStruttura, Struttura } from '@/shared/model/struttura.model';

import StrutturaService from './struttura.service';

export default defineComponent({
  name: 'StrutturaUpdate',
  setup() {
    const strutturaService = inject('strutturaService', () => new StrutturaService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const struttura: Ref<IStruttura> = ref(new Struttura());
    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 retrieveStruttura = async strutturaId => {
      try {
        const res = await strutturaService().find(strutturaId);
        res.createdAt = new Date(res.createdAt);
        res.updatedAt = new Date(res.updatedAt);
        struttura.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.strutturaId) {
      retrieveStruttura(route.params.strutturaId);
    }

    const initRelationships = () => {};

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      nome: {},
      descrizione: {},
      indirizzo: {},
      capienzaMax: {},
      attiva: {},
      fotoUrl: {},
      createdAt: {},
      updatedAt: {},
      disponibilitas: {},
      moduliLiberatories: {},
    };
    const v$ = useVuelidate(validationRules, struttura as any);
    v$.value.$validate();

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