<template>
  <div class="default-header-page">
    <q-breadcrumbs
      v-if="displayBreadcrumbs.length"
      class="q-mb-xs text-secondary"
      :class="$q.screen.lt.sm ? '' : 'q-pl-lg'"
    >
      <q-breadcrumbs-el
        v-for="crumb in displayBreadcrumbs"
        :key="crumb.name || crumb.label"
        :label="crumb.title"
        :to="crumb.name ? { name: crumb.name, params: crumb.params } : null"
      />
    </q-breadcrumbs>

    <div class="flex items-center justify-between">
      <div class="flex items-center" :class="$q.screen.lt.sm ? '' : 'q-pt-md'">
        <span
          v-if="displayTitle"
          class="text-h6 text-primary text-weight-regular"
        >
          {{ displayTitle }}
        </span>
        <div v-else style="width: 280px">
          <q-skeleton type="text" height="40px" />
        </div>
        <q-icon
          v-if="showFilterIcon"
          name="mdi-filter-outline"
          color="background"
          size="sm"
          class="q-ml-sm bg-primary"
          style="border-radius: 8px; padding: 2px"
        />
      </div>
      <div
        class="flex items-center q-pr-sm"
        :class="$q.screen.lt.sm ? '' : 'q-pt-md'"
        style="gap: 8px"
      >
        <slot name="after" />

        <div class="flex items-center no-wrap" style="gap: 12px">
          <!-- Seletor de unidade: aparece apenas quando o usuário tem mais de uma -->
          <template v-if="userUnits.length > 1">
            <DefaultSelect
              :model-value="store.selectedUnit"
              :options="userUnits"
              option-value="id"
              option-label="fantasy_name"
              label="Unidade"
              outlined
              style="width: 280px; flex-shrink: 0"
              @update:model-value="store.setSelectedUnit"
            />
            <q-spinner
              v-if="isUnitLoading"
              color="primary"
              size="18px"
              style="flex-shrink: 0"
            />
          </template>

          <template v-if="$q.screen.gt.sm && lastLoginFormatted">
            <div
              class="column"
              style="line-height: 1.2; white-space: nowrap; flex-shrink: 0"
            >
              <span class="text-caption text-grey-6 text-primary text-center"
                >Ultimo acesso</span
              >
              <span class="text-caption text-primary text-center">{{
                lastLoginFormatted
              }}</span>
            </div>
          </template>

          <div
            class="flex items-center no-wrap"
            style="gap: 2px; flex-shrink: 0"
          >
            <q-btn flat round dense icon="mdi-bell-badge" color="secondary" />
            <q-btn flat round dense icon="mdi-account" color="secondary" />
            <q-btn flat round dense icon="mdi-cog-outline" color="secondary" />
          </div>
        </div>
      </div>
    </div>
    <q-separator class="q-my-sm" />
  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { userStore } from "src/stores/user";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { breadcrumbs, showFilterIcon, title } = defineProps({
  breadcrumbs: {
    type: Array,
    default: null,
  },
  showFilterIcon: {
    type: Boolean,
    default: false,
  },
  title: {
    type: [String, Object],
    default: null,
  },
});

const route = useRoute();
const { t } = useI18n();
const store = userStore();

const userUnits = computed(() => store.user?.units ?? []);

const isUnitLoading = ref(false);
let loadingTimer = null;

watch(
  () => store.selectedUnit?.id,
  (newId, oldId) => {
    if (newId && oldId !== undefined && newId !== oldId) {
      isUnitLoading.value = true;
      clearTimeout(loadingTimer);
      loadingTimer = setTimeout(() => {
        isUnitLoading.value = false;
      }, 1500);
    }
  },
);

const lastLoginFormatted = computed(() => {
  const raw = store.user?.last_login_at;
  if (!raw) return null;
  const d = new Date(raw.replace(" ", "T") + "Z");
  return new Intl.DateTimeFormat("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    timeZone: "America/Sao_Paulo",
  }).format(d);
});

const displayTitle = computed(() => {
  if (title) {
    if (typeof title === "string") return title;
    if (title.translate) return t(title.value);
    return title.value;
  } else if (route.meta?.title) {
    const metaTitle = route.meta.title;
    if (typeof metaTitle === "string") return metaTitle;
    if (metaTitle.translate) return t(metaTitle.value);
    return metaTitle.value;
  }
  return null;
});

const displayBreadcrumbs = computed(() => {
  const items = breadcrumbs?.length ? breadcrumbs : route.meta?.breadcrumbs;

  return (items || []).map((b) => ({
    ...b,
    title: b.translate ? t(b.title) : b.title,
  }));
});
</script>

<style scoped>
.default-header-page {
  padding-left: 4px;
}

.default-header-page :deep(.q-breadcrumbs) {
  display: inline-flex;
  max-width: 100%;
}

.default-header-page :deep(.q-breadcrumbs__el),
.default-header-page :deep(.q-breadcrumbs__separator) {
  flex: 0 0 auto;
  width: auto;
}

.default-header-page :deep(.q-breadcrumbs__el) {
  max-width: max-content;
}

</style>
