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 StrutturaService from '@/entities/struttura/struttura.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { Disponibilita, type IDisponibilita } from '@/shared/model/disponibilita.model';
import { GiornoSettimana } from '@/shared/model/enumerations/giorno-settimana.model';
import { TipoDisponibilita } from '@/shared/model/enumerations/tipo-disponibilita.model';
import { type IStruttura } from '@/shared/model/struttura.model';

import DisponibilitaService from './disponibilita.service';

export default defineComponent({
  name: 'DisponibilitaUpdate',
  setup() {
    const disponibilitaService = inject('disponibilitaService', () => new DisponibilitaService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const disponibilita: Ref<IDisponibilita> = ref(new Disponibilita());

    const strutturaService = inject('strutturaService', () => new StrutturaService());

    const strutturas: Ref<IStruttura[]> = ref([]);
    const giornoSettimanaValues: Ref<string[]> = ref(Object.keys(GiornoSettimana));
    const tipoDisponibilitaValues: Ref<string[]> = ref(Object.keys(TipoDisponibilita));
    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 retrieveDisponibilita = async disponibilitaId => {
      try {
        const res = await disponibilitaService().find(disponibilitaId);
        res.oraInizio = new Date(res.oraInizio);
        res.oraFine = new Date(res.oraFine);
        disponibilita.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.disponibilitaId) {
      retrieveDisponibilita(route.params.disponibilitaId);
    }

    const initRelationships = () => {
      strutturaService()
        .retrieve()
        .then(res => {
          strutturas.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      giornoSettimana: {},
      dataSpecifica: {},
      oraInizio: {},
      oraFine: {},
      orarioInizio: {},
      orarioFine: {},
      tipo: {},
      note: {},
      struttura: {},
    };
    const v$ = useVuelidate(validationRules, disponibilita as any);
    v$.value.$validate();

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