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 UserService from '@/entities/user/user.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useValidation } from '@/shared/composables';
import { Ruolo } from '@/shared/model/enumerations/ruolo.model';
import { type IUtenteApp, UtenteApp } from '@/shared/model/utente-app.model';

import UtenteAppService from './utente-app.service';

export default defineComponent({
  name: 'UtenteAppUpdate',
  setup() {
    const utenteAppService = inject('utenteAppService', () => new UtenteAppService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const utenteApp: Ref<IUtenteApp> = ref(new UtenteApp());
    const userService = inject('userService', () => new UserService());
    const users: Ref<Array<any>> = ref([]);
    const ruoloValues: Ref<string[]> = ref(Object.keys(Ruolo));
    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 retrieveUtenteApp = async utenteAppId => {
      try {
        const res = await utenteAppService().find(utenteAppId);
        utenteApp.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.utenteAppId) {
      retrieveUtenteApp(route.params.utenteAppId);
    }

    const initRelationships = () => {
      userService()
        .retrieve()
        .then(res => {
          users.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      username: {
        required: validations.required(t$('entity.validation.required').toString()),
      },
      email: {
        required: validations.required(t$('entity.validation.required').toString()),
      },
      telefono: {},
      ruolo: {
        required: validations.required(t$('entity.validation.required').toString()),
      },
      attivo: {
        required: validations.required(t$('entity.validation.required').toString()),
      },
      nome: {},
      cognome: {},
      luogoNascita: {},
      dataNascita: {},
      residente: {},
      societa: {},
      sede: {},
      codfiscale: {},
      telefonoSoc: {},
      emailSoc: {},
      internalUser: {},
      liberatories: {},
    };
    const v$ = useVuelidate(validationRules, utenteApp as any);
    v$.value.$validate();

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