<template>
  <q-layout view="hHh Lpr lFf">
    <q-drawer
      :mini="!leftDrawerOpen"
      bordered
      persistent
      :model-value="true"
      :side="preferencesStore.values.drawerSide || 'left'"
    >
      <q-item
        clickable
        v-ripple
        @click="toggleLeftDrawer"
        class="relative"
      >
        <q-item-section avatar>
          <q-icon name="menu" />
        </q-item-section>
        <q-item-section v-if="leftDrawerOpen">
          <q-item-label class="text-h4 absolute-center">
            {{ productName }}
          </q-item-label>
        </q-item-section>
      </q-item>
      <template v-if="authStore.isAuthenticated">
        <q-card
          v-if="leftDrawerOpen"
          bordered
          flat
          class="q-ma-sm text-center relative"
        >
          <q-card-section>
            <q-btn
              class="absolute"
              style="top: 10px; left: 10px;"
              flat
              round
              :to="{ name: 'passkeys' }"
            >
              <q-icon
                name="key"
              />
              <q-tooltip>
                Passkey Management
              </q-tooltip>
            </q-btn>
            <q-btn
              class="absolute"
              style="top: 10px; right: 10px;"
              flat
              round
              :to="{ name: 'userPreferences' }"
            >
              <q-icon
                name="mdi-account-cog"
              />
              <q-tooltip>
                User Preferences
              </q-tooltip>
            </q-btn>
            <q-avatar
              class="bg-primary cursor-pointer text-white"
            >
              <q-icon name="mdi-account" />
            </q-avatar>
            <div class="text-h6">
              {{ authStore.user.username }}
            </div>
            <q-btn
              class="full-width q-mt-sm"
              dense
              outline
              @click="logout"
            >
              Logout
            </q-btn>
          </q-card-section>
        </q-card>
        <q-list
          padding
          class="menu-list"
          v-else
        >
          <q-item
            clickable
            v-ripple
            dense
            :to="{ name: 'passkeys' }"
            class="q-mb-sm"
          >
            <q-tooltip
              anchor="center right"
              self="center left"
            >
              <span>Passkey Management</span>
            </q-tooltip>
            <q-item-section avatar>
              <q-icon name="key" />
            </q-item-section>
            <q-item-section>
              <q-item-label class="text-h6">
                Passkey Management
              </q-item-label>
            </q-item-section>
          </q-item>
          <q-item
            clickable
            v-ripple
            dense
            :to="{ name: 'userPreferences' }"
            class="q-mb-sm"
          >
            <q-tooltip
              anchor="center right"
              self="center left"
            >
              <span>User Preferences</span>
            </q-tooltip>
            <q-item-section avatar>
              <q-icon name="mdi-account-cog" />
            </q-item-section>
            <q-item-section>
              <q-item-label class="text-h6">
                User Preferences
              </q-item-label>
            </q-item-section>
          </q-item>
          <q-item
            clickable
            v-ripple
            dense
            @click="logout"
            class="q-mb-sm"
          >
            <q-tooltip
              anchor="center right"
              self="center left"
            >
              <span>Logout</span>
            </q-tooltip>
            <q-item-section avatar>
              <q-icon name="logout" />
            </q-item-section>
            <q-item-section>
              <q-item-label class="text-h6">
                Logout
              </q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </template>
      <q-separator />
      <q-list
        padding
        class="menu-list"
      >
        <!-- Dynamic Navigation Items -->
        <q-item
          v-for="item in navItems"
          :key="item.name"
          clickable
          v-ripple
          :to="{ name: item.name }"
          dense
        >
          <q-tooltip
            anchor="center right"
            self="center left"
          >
            <span>{{ item.meta.title }}</span>
          </q-tooltip>
          <q-item-section avatar>
            <q-icon :name="item.meta.icon" />
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ item.meta.title }}</q-item-label>
            <q-item-label caption>
              {{ item.meta.caption }}
            </q-item-label>
          </q-item-section>
        </q-item>
      </q-list>
    </q-drawer>

    <q-page-container>
      <router-view />
    </q-page-container>

    <!-- Chat FAB -->
    <q-page-sticky
      v-if="isAuthenticated"
      position="bottom-right"
      :offset="[18, 18]"
      style="z-index: 100000000"
    >
      <q-fab
        v-model="isChatVisible"
        icon="chat"
        class="bg-theme"
        direction="up"
        @click="toggleChat"
      />
    </q-page-sticky>

    <!-- Chat Window Dialog -->
    <q-dialog
      v-model="isChatVisible"
      style="z-index: 100000000"
    >
      <q-card style="width: max(400px, 25%); height: 600px; max-height: 80vh;">
        <q-bar class="bg-primary text-white">
          <div>Chat</div>
          <q-space />
          <q-btn
            dense
            flat
            icon="close"
            @click="toggleChat"
          />
        </q-bar>

        <q-card-section
          class="q-pa-none"
          style="height: calc(100% - 50px);"
        >
          <ChatInterface
            :messages="chatMessages"
            @send-message="handleSendMessage"
          />
        </q-card-section>
        <q-inner-loading :showing="isLoading">
          <q-spinner-gears
            size="50px"
            color="primary"
          />
        </q-inner-loading>
        <q-banner
          v-if="chatError"
          inline-actions
          class="text-white bg-red"
        >
          {{ chatError }}
          <template #action>
            <q-btn
              flat
              color="white"
              label="Dismiss"
              @click="clearError"
            />
          </template>
        </q-banner>
      </q-card>
    </q-dialog>
  </q-layout>
</template>

<script setup>
import axios from 'boot/axios';
import { ref, computed } from 'vue'; // Import computed
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useAuthStore } from 'stores/auth'; // Import the auth store
import { useChatStore } from 'stores/chat'; // Adjust path as needed
import { usePreferencesStore } from 'stores/preferences'; // Import the preferences store
import ChatInterface from 'components/ChatInterface.vue'; // Adjust path as needed
import routes from '../router/routes'; // Import routes

const productName = process.env.PRODUCT_NAME;

const $q = useQuasar();
const leftDrawerOpen = ref(false);
const router = useRouter();
const authStore = useAuthStore(); // Use the auth store
const chatStore = useChatStore();
const preferencesStore = usePreferencesStore(); // Import the preferences store

// Computed properties to get state from the store
const isChatVisible = computed(() => chatStore.isChatVisible);
const chatMessages = computed(() => chatStore.chatMessages);
const isLoading = computed(() => chatStore.isLoading);
const chatError = computed(() => chatStore.error);
const isAuthenticated = computed(() => authStore.isAuthenticated); // Get auth state

// Get the child routes of the main layout
const mainLayoutRoutes = routes.find(r => r.path === '/')?.children || [];

// Compute navigation items based on auth state and route meta
const navItems = computed(() =>
{
  return mainLayoutRoutes.filter(route =>
  {
    const navGroup = route.meta?.navGroup;
    if (!navGroup) return false; // Only include routes with navGroup defined

    if (navGroup === 'always') return true;
    if (navGroup === 'auth' && isAuthenticated.value) return true;
    if (navGroup === 'noAuth' && !isAuthenticated.value) return true;

    return false; // Exclude otherwise
  });
});


// Method to toggle chat visibility via the store action
const toggleChat = () =>
{
  // Optional: Add an extra check here if needed, though hiding the button is primary
  if (isAuthenticated.value)
  {
    chatStore.toggleChat();
  }
};

// Method to send a message via the store action
const handleSendMessage = (messageContent) =>
{
  chatStore.sendMessage(messageContent);
};

// Method to clear errors in the store (optional)
const clearError = () =>
{
  chatStore.error = null; // Directly setting ref or add an action in store
};
function toggleLeftDrawer()
{
  leftDrawerOpen.value = !leftDrawerOpen.value;
}
async function logout()
{
  $q.dialog({
    title: 'Confirm Logout',
    message: 'Are you sure you want to logout?',
    cancel: true,
    persistent: true
  }).onOk(async() =>
  {
    try
    {
      await axios.post('/api/auth/logout');
      authStore.logout();

      $q.notify({
        color: 'positive',
        message: 'Logout successful.',
        icon: 'check_circle'
      });

      router.push({ name: 'login' });
    }
    catch (error)
    {
      console.error('Logout failed:', error);

      $q.notify({
        color: 'negative',
        message: 'Logout failed. Please try again.',
        icon: 'report_problem'
      });
    }
  });
}
</script>

<style lang="scss" scoped>
.q-dialog .q-card {
    overflow: hidden;
}

.menu-list .q-item {
  border-radius: 32px;
  margin: 5px 5px;
}

.menu-list .q-item:first-child {
  margin-top: 0px;
}

.menu-list .q-router-link--active {
  background-color: var(--q-primary);
  color: #fff;
}
</style>
