<template>
  <q-layout class="relative" view="hHh lpR fFf">
    <LeftMenuLayout v-if="$q.screen.gt.sm" />
    <LeftMenuLayoutMobile v-else v-model="leftDrawerOpen" />
    <q-header v-if="!$q.screen.gt.sm" class="bg-transparent" style="padding: 8px; padding-top: calc(env(safe-area-inset-top) + 8px);">
      <q-toolbar class="bg-surface items-center" style="border-radius: 6px !important; padding: 0 8px; min-height: 50px;">
        <q-btn dense flat round size="sm" @click="toggleLeftDrawer">
          <q-icon name="menu" color="primary" size="28px" />
        </q-btn>
        <span class="text-subtitle1 text-weight-bold text-primary q-ml-xs">
          {{ $t('auth.type.associado') }}
        </span>
        <q-space />
        <q-avatar size="40px" color="violet-normal" text-color="white" style="font-size: 20px; font-weight: 700; cursor: default;">
          <img v-if="store.user?.photo_url" :src="store.user.photo_url" style="object-fit: cover; width: 100%; height: 100%;" />
          <template v-else>{{ userInitial }}</template>
        </q-avatar>
      </q-toolbar>
    </q-header>
    <q-page-container>
      <q-page>
        <q-scroll-area
          ref="scrollAreaRef"
          :style="
            !$q.screen.gt.sm
              ? 'height: calc(100dvh - 68px - env(safe-area-inset-top) - env(safe-area-inset-bottom)) !important; width: 100%; overflow-x: hidden;'
              : 'height: calc(100dvh - env(safe-area-inset-bottom)) !important; width: 100%; overflow-x: hidden;'
          "
        >
          <router-view v-slot="{ Component }">
            <Transition mode="out-in">
              <component
                :is="Component"
                style="padding: 20px !important; padding-right: 10px !important"
                :style="[
                  !$q.screen.gt.sm ? 'padding-left: 10px !important;' : '',
                  $q.screen.gt.sm ? 'padding-top: calc(env(safe-area-inset-top) + 20px) !important;' : '',
                ]"
              />
            </Transition>
          </router-view>
        </q-scroll-area>
      </q-page>
    </q-page-container>
  </q-layout>
</template>

<script setup>
import { ref, computed, onMounted, useTemplateRef, watch } from "vue";
import { useRoute } from "vue-router";
import { useQuasar } from "quasar";
import { userStore } from "src/stores/user";
import { getMyUnreadNotificationsAssociado } from "src/api/notification";
import { getPendingEvaluationAssociado } from "src/api/evaluation";
import { getMyAppointments } from "src/api/appointment";
import UnreadNotificationsDialog from "src/components/UnreadNotificationsDialog.vue";
import CompleteProfileDialog from "src/components/CompleteProfileDialog.vue";
import EvaluationDialog from "src/components/EvaluationDialog.vue";
import PendingExamsDialog from "src/components/PendingExamsDialog.vue";

import LeftMenuLayout from "src/components/layout/LeftMenuLayout.vue";
import LeftMenuLayoutMobile from "src/components/layout/LeftMenuLayoutMobile.vue";

const route = useRoute();
const $q = useQuasar();
const store = userStore();

const leftDrawerOpen = ref(false);
const scrollAreaRef = useTemplateRef("scrollAreaRef");

const userInitial = computed(() => {
  const name = store.user?.name || "";
  return name.charAt(0).toUpperCase() || "A";
});

let oldValue = route.path;

const toggleLeftDrawer = () => {
  leftDrawerOpen.value = !leftDrawerOpen.value;
};

const isProfileIncomplete = (user) => {
  return (
    !user.terms_accepted_at ||
    !user.photo_url ||
    !user.name ||
    !user.cpf ||
    !user.email ||
    !user.phone ||
    !(user.position_id ?? user.position?.id) ||
    !(user.sector_id   ?? user.sector?.id)
  );
};

const checkPendingExams = async () => {
  try {
    const appointments = await getMyAppointments();
    const pending = (appointments ?? []).filter((a) => {
      const status = typeof a.status === "object" ? a.status?.value : a.status;
      return status === "aguardando_aceite";
    });

    if (pending.length > 0) {
      $q.dialog({ component: PendingExamsDialog, componentProps: { exams: pending } });
    }
  } catch {
    // silent
  }
};

const checkUnreadNotifications = async () => {
  try {
    const unread = await getMyUnreadNotificationsAssociado();
    if (unread && unread.length > 0) {
      $q.dialog({ component: UnreadNotificationsDialog }).onOk(() => checkPendingExams());
      return;
    }
  } catch {
    // silent
  }

  await checkPendingExams();
};

const checkPendingEvaluation = async () => {
  try {
    const campaign = await getPendingEvaluationAssociado();

    if (!campaign) {
      await checkUnreadNotifications();
      return;
    }

    $q.dialog({
      component: EvaluationDialog,
      componentProps: { campaign },
    }).onOk(() => checkUnreadNotifications());
  } catch {
    await checkUnreadNotifications();
  }
};

onMounted(async () => {
  const user = store.user;
  if (user && isProfileIncomplete(user)) {
    $q.dialog({ component: CompleteProfileDialog })
      .onOk(() => checkPendingEvaluation());
  } else {
    await checkPendingEvaluation();
  }
});

watch(route, (value) => {
  if (oldValue.path != value.path) {
    scrollAreaRef.value.setScrollPosition("vertical", 0, 0);
    scrollAreaRef.value.setScrollPosition("horizontal", 0, 0);
  }
  oldValue = value.path;
});
</script>
<style scoped>
.v-enter-active {
  opacity: 1;
  transition: all 0.15s ease-in;
}

.v-leave-active {
  opacity: 1;
  transition: all 0.15s ease-out;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  transition: all 0.15s ease-in;
}

.v-leave-to {
  transition: all 0.15s ease-out;
}
</style>
