<template>
  <Transition name="focus-mode">
    <div class="fixed inset-0 z-50 bg-white flex flex-col h-full">
      <!-- Header -->
      <div class="flex items-center border-b bg-gray-50 h-[56px] py-1.5 px-3 justify-between">
        <div class="flex items-center space-x-2 sm:space-x-4 min-w-0">
          <Button variant="ghost" size="sm" @click="handleClose" class="shrink-0">
            <i class="dku-icon-chevron-left-16" />
            <span>Back</span>
          </Button>
        </div>
        <div class="flex items-center space-x-2 shrink-0">
          <!-- Indexing Status Badge -->
          <Badge v-if="isIndexing(indexing?.status)" class="animate-pulse">
            <Loader2 class="w-3 h-3 animate-spin mr-1" />
            Processing...
          </Badge>
        </div>
      </div>

      <!-- Main Content -->
      <div class="flex-1 overflow-y-auto py-5 md:px-14 h-full">
        <div class="flex gap-6 h-full">
          <div class="space-y-6 px-6 md:px-2.5 flex-1 mx-auto">
            <!-- Desktop: Two-column layout; Mobile: Tabs -->
            <div v-if="isDesktop" class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div class="min-w-0">
                <DocumentsUpload
                  :is-indexing-busy="isIndexingBusy"
                  :agent-id="agentId"
                  :agent-name="agentName"
                  @confirm-delete="confirmDelete"
                />
              </div>
              <div class="min-w-0 md:h-fit">
                <InstructionsConfig
                  :doc-retrieval-prompt="localDocRetrievalPrompt"
                  @update:doc-retrieval-prompt="(prompt: string) => localDocRetrievalPrompt = prompt"
                />
              </div>
            </div>

            <Tabs v-else v-model="activeTab" class="flex-1 flex flex-col">
              <TabsList class="w-full justify-start shrink-0">
                <TabsTrigger
                  value="details"
                  class="flex items-center gap-2 hover:text-primary-hover transition-colors duration-200"
                >
                  Documents
                </TabsTrigger>
                <TabsTrigger
                  value="instructions"
                  class="flex items-center gap-2 hover:text-primary-hover transition-colors duration-200"
                >
                  Instructions
                </TabsTrigger>
              </TabsList>

              <TabsContent value="details" class="flex-1">
                <DocumentsUpload
                  :is-indexing-busy="isIndexingBusy"
                  :agent-id="agentId"
                  :agent-name="agentName"
                  @confirm-delete="confirmDelete"
                />
              </TabsContent>

              <TabsContent value="instructions">
                <InstructionsConfig
                  :doc-retrieval-prompt="localDocRetrievalPrompt"
                  @update:doc-retrieval-prompt="(prompt: string) => localDocRetrievalPrompt = prompt"
                />
              </TabsContent>
            </Tabs>
          </div>

          <!-- Delete Confirmation Dialog -->
          <AlertDialog v-model:open="deleteDialogOpen">
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle
                  ><i class="dku-icon-trash-16 mr-2"></i>Delete Document</AlertDialogTitle
                >
                <AlertDialogDescription>
                  Delete <strong>{{ docToDelete?.name }}</strong
                  >. This action cannot be undone
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  @click="deleteDocument"
                  class="bg-red-600 text-white hover:bg-red-700"
                >
                  Delete
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { Loader2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { isIndexing } from '@/constants/indexing'
import type { DocumentItem } from '@/types/document'
import { useIndexingStore, type JobBlob } from '@/store/indexingStore'
import DocumentsUpload from './DocumentsUpload.vue'
import InstructionsConfig from './InstructionsConfig.vue'
import { useSidebar } from '@/components/ui/sidebar'
import { Badge } from '@/components/ui/badge'
import { API } from '@/Api'
import { toast } from 'vue-sonner'
import { DOC_DELETE_FAILED, ERROR_409 } from '@/constants/notifs'

// Props
const props = defineProps<{
  agentId: string
  agentName: string
  indexing?: JobBlob
  docRetrievalPrompt: string
}>()

// Emits
const emit = defineEmits<{
  (e: 'delete-docs', docs: string[]): void
  (e: 'update:doc-retrieval-prompt', prompt: string): void
  (e: 'close'): void
}>()

// State
const activeTab = ref('details')
const deleteDialogOpen = ref(false)
const docToDelete = ref<DocumentItem | null>(null)
const localDocRetrievalPrompt = ref(props.docRetrievalPrompt)
const { isDesktop } = useSidebar()

// Watch for prop changes
watch(
  () => props.docRetrievalPrompt,
  (newVal) => {
    localDocRetrievalPrompt.value = newVal
  }
)

// Watch for local changes and emit
watch(localDocRetrievalPrompt, (newVal) => {
  emit('update:doc-retrieval-prompt', newVal)
})

// Computed
const isIndexingBusy = computed(() => isIndexing(props.indexing?.status))

// Methods
function handleClose() {
  emit('close')
}

function confirmDelete(doc: DocumentItem) {
  docToDelete.value = doc
  deleteDialogOpen.value = true
}

async function deleteDocument() {
  if (!docToDelete.value || docToDelete.value.pendingUpload) return
  emit('delete-docs', [docToDelete.value.name])
  try {
    const { data } = await API.deleteAgentDocument(props.agentId, docToDelete.value.name)
    // todo update store
    // Update indexing store and broadcast to other components
    const idxStore = useIndexingStore()
    idxStore.track(props.agentId, data.indexing, props.agentName)
    window.dispatchEvent(
      new CustomEvent('docs-updated', {
        detail: { agentId: props.agentId, docs: data.documents, indexing: data.indexing },
      })
    )
    if (data.indexing) {
      toast.success('Document queued for deletion and re-processing')
    } else {
      toast.success('Document deleted successfully')
    }
  } catch (err: any) {
    toast.error(err.response?.status === 409 ? ERROR_409 : DOC_DELETE_FAILED)
  } finally {
    deleteDialogOpen.value = false
    docToDelete.value = null
  }
}

// Sync across components
function handleDocsUpdated(e: any) {
  const d = e.detail
  if (!d || d.agentId !== props.agentId) return
  // Update local state and emit to parent
  // emit('update:indexing', d.indexing)
}

onMounted(() => window.addEventListener('docs-updated', handleDocsUpdated))
onBeforeUnmount(() => window.removeEventListener('docs-updated', handleDocsUpdated))
</script>

<style scoped>
.focus-mode-enter-active,
.focus-mode-leave-active {
  transition: all 0.3s ease;
}

.focus-mode-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.focus-mode-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* Ensure proper height on mobile */
@media (max-width: 640px) {
  .h-1\/2 {
    height: 50%;
  }
}
</style>
