import { type ComputedRef, type Ref, defineComponent, inject, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';

import { useLoginModal } from '@/account/login-modal';
import UtenteAppService from '@/entities/utente-app/utente-app.service';

export default defineComponent({
  setup() {
    const { showLogin } = useLoginModal();
    const authenticated = inject<ComputedRef<boolean>>('authenticated');
    const username = inject<ComputedRef<string>>('currentUsername');
    const utenteAppService = inject<UtenteAppService>('utenteAppService', () => new UtenteAppService());

    const profileIncomplete: Ref<boolean> = ref(false);
    const checkingProfile: Ref<boolean> = ref(false);

    const checkProfileCompletion = async () => {
      if (!authenticated.value) {
        profileIncomplete.value = false;
        return;
      }

      try {
        checkingProfile.value = true;
        const utenteApp = await utenteAppService.getCurrentUser();

        // Check if essential profile fields are missing
        if (
          !utenteApp ||
          !utenteApp.nome ||
          !utenteApp.cognome ||
          !utenteApp.dataNascita ||
          !utenteApp.luogoNascita ||
          !utenteApp.residente ||
          !utenteApp.telefono
        ) {
          profileIncomplete.value = true;
        } else {
          profileIncomplete.value = false;
        }
      } catch (error) {
        // If UtenteApp doesn't exist, profile is incomplete
        profileIncomplete.value = true;
      } finally {
        checkingProfile.value = false;
      }
    };

    onMounted(() => {
      checkProfileCompletion();
    });

    return {
      authenticated,
      username,
      showLogin,
      profileIncomplete,
      checkingProfile,
      t$: useI18n().t,
    };
  },
});
