<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { SidebarProvider } from '@/components/ui/sidebar'
import { Toaster } from 'vue-sonner'
import { TooltipProvider } from '@/components/ui/tooltip'
import { v4 as uuidv4 } from 'uuid'
import { useRouter } from 'vue-router'
import AccessDeniedDialog from '@/components/AccessDeniedDialog.vue'
import UnifiedSidebar from '@/components/UnifiedSidebar.vue'
import { useConversationStore } from './store/conversationStore'
import ErrorDialog from './components/ErrorDialog.vue'
import { API } from '@/Api'

// Use the centralized chat store
const conversationStore = useConversationStore()
const router = useRouter()

// References to components
const unifiedSidebarRef = ref<InstanceType<typeof UnifiedSidebar> | null>(null)

// When an agent is clicked, start a new conversation with that agent preselected.
function onAgentSelect(agentId: string) {
  const conversationId = uuidv4()
  conversationStore.setAgentIds([agentId])
  conversationStore.setActiveConversation(conversationId)
}

// When selecting an existing conversation from the list, update the store accordingly.
function onSelectConversation(payload: {
  conversationId: string
  agentIds: string[]
  modeAgents: boolean
  selectedLlm: string | null
}) {
  conversationStore.setActiveConversation(payload.conversationId)
  router.push({ name: 'Conversations' })
}

// When a conversation is deleted, clear it if currently active.
function handleConversationDeleted(deletedId?: string) {
  const isInDeleteAllMode = deletedId === undefined
  const currentConversationId = conversationStore.activeConversationId
  if (isInDeleteAllMode && currentConversationId) {
    const currentConversationExists =
      (conversationStore.getConversation(currentConversationId)?.messages?.length ?? 0) > 0
    if (currentConversationExists) {
      conversationStore.clearConversationSelection()
      router.push({ name: 'Home' })
    }
  } else {
    if (currentConversationId === deletedId) {
      conversationStore.clearConversationSelection()
      router.push({ name: 'Home' })
    }
  }
}

// When clicking on "New" from the header, start a fresh conversation.
function handleNewConversation() {
  conversationStore.clearConversationSelection()
  window.dispatchEvent(new CustomEvent('reset-home-input'))
}

// When clicking on "Agents Library", clear the current conversation
function handleViewLibrary() {
  conversationStore.clearConversationSelection()
  router.push({ name: 'AgentLibrary' })
}

// When clicking on "Agents Library" for My Agents tab
function handleViewLibraryMyAgents() {
  conversationStore.clearConversationSelection()
  router.push({ name: 'AgentLibrary', query: { tab: 'myAgents' } })
}

function handleViewMonitoring() {
  conversationStore.clearConversationSelection()
}

function handleNewAgent() {
  conversationStore.clearConversationSelection()
}

function handleEditAgent(id: string) {
  conversationStore.clearConversationSelection()
  router.push({ name: 'EditAgent', params: { id } })
}

function handleViewHome() {
  conversationStore.clearConversationSelection()
  window.dispatchEvent(new CustomEvent('reset-home-input'))
}

function handleViewAdminSettings() {
  conversationStore.clearConversationSelection()
  router.push({ name: 'AdminSettings' })
}
const loaded = ref(null as boolean | null)
const openErrorDialog = ref(false)
watch(
  () => loaded.value,
  (newVal) => {
    if (newVal) {
      openErrorDialog.value = false
    } else {
      openErrorDialog.value = true
    }
  }
)
const isProjectAdmin = ref(false)
onMounted(async () => {
  const user = await API.getCurrentUser()
  isProjectAdmin.value = !!user?.data?.hasWriteAccess
})
function goAdmin() {
  openErrorDialog.value = false
  router.push({ name: 'AdminSettings' })
}
</script>

<template>
  <TooltipProvider>
    <SidebarProvider>
      <Toaster />
      <div class="flex h-screen w-full">
        <!-- Unified Sidebar - handles both agents and admin -->
        <UnifiedSidebar
          ref="unifiedSidebarRef"
          :selectedConversationId="conversationStore.activeConversationId"
          @selectAgent="onAgentSelect"
          @selectConversation="onSelectConversation"
          @conversationDeleted="handleConversationDeleted"
          @new-conversation="handleNewConversation"
          @view-library="handleViewLibrary"
          @view-library-my-agents="handleViewLibraryMyAgents"
          @view-monitoring="handleViewMonitoring"
          @new-agent="handleNewAgent"
          @edit-agent="handleEditAgent"
          @view-home="handleViewHome"
          @view-admin-settings="handleViewAdminSettings"
        />

        <!-- Right: Main panel -->
        <main class="flex-1 flex flex-col bg-white h-full overflow-x-auto">
          <!-- Page content takes remaining space -->
          <router-view @loaded="(val: boolean) => loaded = val" />
        </main>
      </div>
      <!-- TODO: Current condition for showing the access denied dialog is when user profile is None
       But in this case the user can't access the webapps. -->
      <AccessDeniedDialog :open="false" />
      <!-- <BackendIsStartingDialog :open="!hasUserBeenSet" v-if="loaded" /> -->
      <ErrorDialog
        :open="openErrorDialog"
        title="We’re having trouble loading the app"
        footerText="Close"
        @back="openErrorDialog = false"
      >
        <span>
          Something went wrong while loading the application. <br />
          The service may not be ready or some settings may be missing.<br />
          Please make sure the service is running
          {{
            isProjectAdmin
              ? 'or configure the required settings in the'
              : 'or contact your administrator.'
          }}
        </span>
        <a
          v-if="isProjectAdmin"
          @click="goAdmin"
          class="text-primary-hover underline ml-1 inline-flex cursor-pointer"
          >Admin Settings</a
        >
      </ErrorDialog>
    </SidebarProvider>
  </TooltipProvider>
</template>
