<template>
  <div class="q-pa-sm">
    <q-breadcrumbs
      v-if="displayBreadcrumbs != null"
      class="q-mb-xs text-secondary flex items-center"
      :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
      v-else
      style="max-width: 180px"
      :class="$q.screen.lt.sm ? '' : 'q-pl-lg'"
    >
      <q-skeleton type="text" />
    </div>

    <div class="flex items-center justify-between">
      <div
        class="flex items-center q-pl-xs"
        :class="$q.screen.lt.sm ? '' : 'q-pt-md'"
      >
        <span v-if="title" class="text-h6 text-primary text-weight-regular">
          {{ title }}
        </span>
        <div v-else style="width: 280px">
          <q-skeleton type="text" height="40px" />
        </div>
        <q-icon
          v-if="showFilterIcon"
          name="mdi-filter-outline"
          :color="filterOpen ? 'background' : 'primary'"
          size="sm"
          class="q-ml-sm cursor-pointer"
          :class="filterOpen ? 'bg-primary' : ''"
          :style="
            filterOpen
              ? 'border-radius: 8px; padding: 2px'
              : 'border-radius: 8px; padding: 2px; border: 1.5px solid var(--q-primary)'
          "
          @click="$emit('show-filter')"
        />
      </div>
      <div
        class="flex items-center q-pr-sm"
        :class="$q.screen.lt.sm ? '' : 'q-pt-md'"
      >
        <div class="flex items-center no-wrap" style="gap: 12px">
          <div
            class="flex items-center no-wrap q-gutter-x-md q-px-sm q-ml-md"
            style="flex-shrink: 0"
          >
            <q-img
              :src="user?.avatar_url || 'icons/user-icon.jpg'"
              class="avatar-circle"
            />


            <div
              v-if="$q.screen.gt.xs"
              class="column q-gutter-y-none"
              style="white-space: nowrap"
            >
              <span class="text-body2 text-center">{{ user?.name }}</span>
            </div>
          </div>

          <template v-if="$q.screen.gt.sm && lastLoginFormatted">
            <q-separator
              vertical
              style="height: 36px; width: 2px; flex-shrink: 0"
              color="dark"
            />

            <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"
          >
            <!-- Notificações -->
            <q-btn flat round dense icon="mdi-bell-badge" color="secondary">
              <q-badge
                v-if="unreadCount > 0"
                color="negative"
                floating
                rounded
                :label="unreadCount"
              />
              <q-menu
                anchor="bottom right"
                self="top right"
                :offset="[0, 8]"
                class="header-menu"
                @before-show="loadNotifications"
              >
                <div class="notifications-panel">
                  <div class="row items-center justify-between q-px-md q-py-sm">
                    <span class="text-subtitle2 text-primary text-weight-medium">
                      Notificações
                    </span>
                    <q-btn
                      flat
                      dense
                      no-caps
                      size="sm"
                      color="secondary"
                      label="Marcar tudo como lido"
                      :disable="unreadCount === 0"
                      @click="markAllAsRead"
                    />
                  </div>
                  <q-separator />

                  <q-scroll-area
                    v-if="notifications.length"
                    style="height: 360px"
                    :thumb-style="{ width: '5px', borderRadius: '4px' }"
                  >
                  <q-list separator>
                    <q-item
                      v-for="n in notifications"
                      :key="n.id"
                      v-close-popup
                      clickable
                      :class="!n.is_read ? 'bg-grey-2' : ''"
                      @click="openNotification(n)"
                    >
                      <q-item-section avatar top>
                        <q-icon
                          :name="iconFor(n.notification_type)"
                          :color="n.is_read ? 'grey-5' : 'secondary'"
                          size="24px"
                        />
                      </q-item-section>
                      <q-item-section>
                        <q-item-label
                          class="text-primary"
                          :class="!n.is_read ? 'text-weight-medium' : ''"
                        >
                          {{ n.title }}
                        </q-item-label>
                        <q-item-label caption lines="2">
                          {{ n.message }}
                        </q-item-label>
                        <q-item-label caption class="text-grey-6 q-mt-xs">
                          {{ formatNotificationDate(n.created_at) }}
                        </q-item-label>
                      </q-item-section>
                      <q-item-section v-if="!n.is_read" side top>
                        <q-badge color="negative" rounded style="padding: 4px" />
                      </q-item-section>
                    </q-item>
                  </q-list>
                  </q-scroll-area>

                  <div
                    v-else
                    class="column items-center justify-center q-pa-lg text-grey-6"
                  >
                    <q-icon name="mdi-bell-off-outline" size="32px" />
                    <span class="text-caption q-mt-sm">Sem notificações</span>
                  </div>
                </div>
              </q-menu>
            </q-btn>

            <!-- Perfil do usuário -->
            <q-btn flat round dense icon="mdi-account" color="secondary">
              <q-menu
                anchor="bottom right"
                self="top right"
                :offset="[0, 8]"
                class="header-menu"
              >
                <div class="profile-panel q-pa-md">
                  <div class="row items-center no-wrap q-gutter-x-md">
                    <q-img
                      :src="user?.avatar_url || 'icons/user-icon.jpg'"
                      class="avatar-circle"
                    />
                    <div class="column" style="min-width: 0">
                      <span class="text-body2 text-primary text-weight-medium ellipsis">
                        {{ user?.name || "Usuário" }}
                      </span>
                      <span class="text-caption text-grey-6 ellipsis">
                        {{ user?.email }}
                      </span>
                    </div>
                  </div>
                  <q-separator class="q-my-md" />
                  <q-btn
                    v-close-popup
                    flat
                    no-caps
                    align="left"
                    class="full-width"
                    color="primary"
                    icon="mdi-account-edit-outline"
                    label="Editar"
                    @click="goToEditProfile"
                  />
                </div>
              </q-menu>
            </q-btn>

            <!-- Configurações -->
            <q-btn flat round dense icon="mdi-cog-outline" color="secondary">
              <q-menu
                anchor="bottom right"
                self="top right"
                :offset="[0, 8]"
                class="header-menu"
              >
                <div class="settings-panel q-pa-md">
                  <div class="column q-mb-md">
                    <span class="text-caption text-grey-6">Unidade</span>
                    <span class="text-body2 text-primary text-weight-medium">
                      {{ unitLabel }}
                    </span>
                  </div>
                  <q-separator class="q-mb-md" />
                  <q-btn
                    v-close-popup
                    flat
                    no-caps
                    align="left"
                    class="full-width"
                    color="negative"
                    icon="mdi-logout"
                    label="Sair"
                    @click="logoutFn"
                  />
                </div>
              </q-menu>
            </q-btn>
          </div>
        </div>
        <slot name="after" />
      </div>
    </div>
    <q-separator class="q-my-sm" />
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { userStore } from "src/stores/user";
import { useAuth } from "src/composables/useAuth";
import { formatUnitName } from "src/helpers/utils";
import {
  getMyNotifications,
  getUnreadCount,
  markNotificationRead,
  markAllNotificationsRead,
} from "src/api/notification";
import { socket, joinRoom, leaveRoom } from "src/boot/socket.io";

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

defineEmits(["show-filter"]);

const store = userStore();
const router = useRouter();
const { logout } = useAuth();
const user = computed(() => store.user);

// Unidade exibida em Configurações. Sem unidade vinculada = matriz.
const unitLabel = computed(() => {
  const units = store.user?.units ?? [];
  if (!units.length) return "Franqueadora / Matriz";
  return units.map((unit) => formatUnitName(unit)).join(", ");
});

// ------------------- Notificações (sino) -------------------
const notifications = ref([]);
const unreadCount = ref(0);

// Ícone por tipo de notificação (fallback genérico).
const NOTIFICATION_ICONS = {
  support_ticket_created: "mdi-lifebuoy",
  support_ticket_reply: "mdi-message-reply-text-outline",
  kanban_created: "mdi-clipboard-plus-outline",
  kanban_reply: "mdi-comment-text-outline",
  kanban_status_changed: "mdi-swap-horizontal",
  tbr_month_closed: "mdi-cash-multiple",
  account_payable_created: "mdi-file-document-plus-outline",
  payment_credited: "mdi-cash-check",
};

const iconFor = (type) => NOTIFICATION_ICONS[type] || "mdi-bell-outline";

const loadUnreadCount = async () => {
  try {
    unreadCount.value = await getUnreadCount();
  } catch (e) {
    console.error("Falha ao carregar contador de notificações:", e);
  }
};

const loadNotifications = async () => {
  try {
    notifications.value = await getMyNotifications();
  } catch (e) {
    console.error("Falha ao carregar notificações:", e);
  }
};

const markAllAsRead = async () => {
  try {
    await markAllNotificationsRead();
    notifications.value.forEach((n) => (n.is_read = true));
    unreadCount.value = 0;
  } catch (e) {
    console.error("Falha ao marcar todas como lidas:", e);
  }
};

const openNotification = async (n) => {
  if (!n.is_read) {
    try {
      await markNotificationRead(n.id);
      n.is_read = true;
      unreadCount.value = Math.max(0, unreadCount.value - 1);
    } catch (e) {
      console.error("Falha ao marcar como lida:", e);
    }
  }
  if (n.url) router.push(n.url);
};

const formatNotificationDate = (raw) => {
  if (!raw) return "";
  // Backend envia "Y-m-d H:i:s" (horário local do servidor / America/Sao_Paulo).
  const d = new Date(String(raw).replace(" ", "T"));
  return new Intl.DateTimeFormat("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(d);
};

// Realtime: entra na sala do usuário e atualiza ao receber evento (best-effort).
const userRoom = computed(() =>
  user.value?.id ? `user.${user.value.id}` : null,
);

const onRealtimeNotification = () => {
  loadUnreadCount();
  loadNotifications();
};

onMounted(() => {
  loadUnreadCount();
  if (userRoom.value) {
    joinRoom(userRoom.value);
    socket.on("notification", onRealtimeNotification);
  }
});

onBeforeUnmount(() => {
  if (userRoom.value) {
    socket.off("notification", onRealtimeNotification);
    leaveRoom(userRoom.value);
  }
});

const goToEditProfile = () => {
  if (!user.value?.id) return;
  router.push({ name: "UserEditPage", params: { id: user.value.id } });
};

const logoutFn = async () => {
  await logout();
  router.push({ name: "LoginPage" });
};

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

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

const displayBreadcrumbs = computed(() => {
  if (!breadcrumbs && breadcrumbs?.length <= 0) {
    return null;
  } else if (breadcrumbs && breadcrumbs?.length > 0) {
    return (breadcrumbs || []).map((b) => {
      if (b.translate) {
        return t(b.title);
      } else {
        return b.title;
      }
    });
  }
  if (!route.meta?.breadcrumbs && route.meta?.breadcrumbs?.length <= 0) {
    return null;
  } else if (route.meta?.breadcrumbs && route.meta?.breadcrumbs?.length > 0) {
    return (route.meta?.breadcrumbs || []).map((b) => {
      if (b.translate) {
        return {
          ...b,
          title: t(b.title),
        };
      } else {
        return {
          ...b,
          title: b.title,
        };
      }
    });
  }
  return null;
});
</script>

<style scoped>
.avatar-circle {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  flex-shrink: 0;
}

.header-menu {
  border-radius: 10px;
}

.notifications-panel {
  width: 340px;
  max-width: 90vw;
}

.profile-panel,
.settings-panel {
  width: 260px;
  max-width: 90vw;
}
</style>
