<script setup lang="ts">
import { ref } from 'vue'
import { SidebarProvider } from '@/components/ui/sidebar'
import { Toaster } from 'vue-sonner'
import { TooltipProvider } from '@/components/ui/tooltip'
import { useUserStore } from '@/store/userStore'
import { useChatStore } from '@/store/chatStore'
import { v4 as uuidv4 } from 'uuid'
import { useRouter } from 'vue-router'
import AccessDeniedDialog from '@/components/AccessDeniedDialog.vue'
import AgentsSidebar from '@/components/AgentsSidebar.vue'
import { useConversationStore } from './store/conversationStore'

const userStore = useUserStore()
const userHasAccess = userStore.userHasAccess

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

// References to components
const agentsSidebarRef = ref<InstanceType<typeof AgentsSidebar> | null>(null)

// When an agent is clicked, start a new conversation with that agent preselected.
function onAgentSelect(agentId: string) {
  const conversationId = uuidv4()
  chatStore.setConversation(conversationId, [agentId])
  conversationStore.setActiveConversation(conversationId)
  // Navigation is handled by the sidebar component
}

// When selecting an existing conversation from the list, update the store accordingly.
function onSelectConversation(payload: { conversationId: string; agentIds: string[] }) {
  chatStore.setConversation(payload.conversationId, payload.agentIds)
  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 = chatStore.conversationId
  if (isInDeleteAllMode && currentConversationId) {
    const currentConversationExists =
      (conversationStore.getConversation(currentConversationId)?.messages?.length ?? 0) > 0
    if (currentConversationExists) {
      chatStore.clearConversation()
      router.push({ name: 'Home' })
    }
  } else {
    if (currentConversationId === deletedId) {
      chatStore.clearConversation()
      router.push({ name: 'Home' })
    }
  }
}

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

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

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

// TODO: refactor as one function for all three
function handleViewMonitoring() {
  chatStore.clearConversation()
  conversationStore.setActiveConversation(null)
}

function handleNewAgent() {
  chatStore.clearConversation()
  conversationStore.setActiveConversation(null)
}

function handleEditAgent() {
  chatStore.clearConversation()
  conversationStore.setActiveConversation(null)
}

function handleViewHome() {
  chatStore.clearConversation()
  conversationStore.setActiveConversation(null)
  window.dispatchEvent(new CustomEvent('reset-home-input'))
}
</script>

<template>
  <TooltipProvider>
    <SidebarProvider>
      <Toaster />
      <div class="flex h-screen w-full">
        <!-- Left: Agents + Conversations sidebar -->
        <AgentsSidebar
          ref="agentsSidebarRef"
          :selectedConversationId="chatStore.conversationId"
          @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"
        />

        <!-- Right: Main panel -->
        <main class="flex-1 flex flex-col bg-white h-full">
          <!-- Page content takes remaining space -->
          <router-view />
        </main>
      </div>
      <AccessDeniedDialog :open="!userHasAccess" />
    </SidebarProvider>
  </TooltipProvider>
</template>
