<template>
  <AccordionItem
    :disabled="props.disabled"
    value="documents"
    class="border rounded-lg overflow-hidden data-[state=open]:border-primary data-[state=open]:border-b"
  >
    <AccordionTrigger class="p-4 group-hover:no-underline hover:bg-gray-100/30 transition-colors">
      <div class="flex items-center justify-between w-full">
        <div class="flex flex-col space-x-3">
          <div class="flex flex-row items-center justify-start">
            <i class="dku-icon-file-text-16 text-primary mr-2 my-auto"></i>
            <div class="text-base text-base-foreground my-auto inline-flex items-center gap-2">
              <div>Documents</div>
              <Badge class="bg-gray-100 text-base-foreground">
                {{ documents?.length ?? 0 }} uploaded
              </Badge>
              <Badge class="text-[#0B590B] bg-[#E7EEE7]">
                {{ documents?.filter((doc) => doc.active).length ?? 0 }} active
              </Badge>
            </div>
          </div>
          <div class="ml-7">
            <p class="text-sm text-foreground mt-0.5">
              Adding documents allows the assistant to provide more accurate, context-aware answers
              based on your content
            </p>
          </div>
        </div>
      </div>
      <template #icon>
        <i
          class="dku-icon-chevron-down-16 text-muted-foreground pointer-events-none text-xl shrink-0 translate-y-0.5 transition-transform duration-200"
        ></i>
      </template>
    </AccordionTrigger>
    <AccordionContent class="px-4 pb-4 pt-2 bg-white">
      <div class="space-y-4">
        <!-- Document Manager -->
        <div class="flex flex-col flex-1 overflow-hidden mb-5">
          <p class="text-muted-foreground">Supports PDF, DOCX, PPTX, JPG/PNG, TXT, MD, HTML</p>
          <div class="flex-1 min-h-0">
            <DocumentManager
              class="h-full"
              :key="`doc-manager-${agentId}-${indexing?.status || 'idle'}`"
              :agent-id="agentId"
              :agent-name="agentName"
              :initial-documents="normalize(documents)"
              :initial-indexing="indexing"
              :upload-disabled="props.disabled"
            />
          </div>
        </div>

        <!-- Document-retrieval System Prompt -->
        <div>
          <div class="flex items-center mb-1">
            <Label class="font-medium">Documents description</Label>
          </div>
          <Alert variant="info" class="mb-1 py-2 px-2" collapsible default-collapsed>
            <i class="dku-icon-info-circle-outline-16"></i>
            <AlertTitle
              >Help the AI understand what kinds of information this document set is
              providing</AlertTitle
            >
            <AlertDescription>
              Tips for effective instructions 
              <br />
              • Describe in details the content of your documents
              <br />
              • Keep your description up to date as you add/remove documents
              <br />
              • Explain when to use information provided by these documents
            </AlertDescription>
          </Alert>
          <Textarea
            :disabled="props.disabled"
            v-model="modelValue.kbDescription"
            rows="4"
            placeholder="Description of your documents"
            class="w-full !border !border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 text-sm py-2 px-3 resize-y placeholder-gray-400 placeholder-opacity-50 min-h-[120px]"
            @input="handleKbDescriptionInput"
          />
        </div>

        <div class="flex justify-end">
          <Button size="sm" variant="ghost" @click.stop="openDocumentsFocus">
            <i class="dku-icon-gear-16 mr-1 text-primary"></i>
            <span>Advanced Mode</span>
            <i class="dku-icon-chevron-right-16"></i>
          </Button>
        </div>
      </div>
    </AccordionContent>
  </AccordionItem>

  <!-- Documents Advanced Mode -->
  <DocumentsAdvancedMode
    v-if="showDocumentsFocus"
    :agent-id="agentId"
    :agent-name="agentName"
    :indexing="indexing"
    :doc-retrieval-prompt="modelValue.kbDescription"
    :upload-disabled="agentName.trim() === ''"
    @update:doc-retrieval-prompt="(prompt: string) => emit('update:modelValue', { ...props.modelValue, kbDescription: prompt })"
    @close="showDocumentsFocus = false"
  />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import DocumentsAdvancedMode from '../AgentConfiguration/Documents/DocumentsAdvancedMode.vue'
import type { DocumentItem } from '@/types/document'
import { Alert, AlertTitle, AlertDescription } from '../ui/alert'
import { Badge } from '@/components/ui/badge'
import DocumentManager from '@/components/DocumentsUpload/DocumentManager.vue'
interface Props {
  modelValue: {
    kbDescription: string
  }
  agentId: string
  agentName: string
  documents?: any[]
  indexing?: { status: string }
  disabled?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: Props['modelValue']): void
}>()

const showDocumentsFocus = ref(false)

// Create a computed property to handle v-model
const modelValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

/** Normalize for DocumentManager **/
function normalize(docs: any[] = []): DocumentItem[] {
  return docs.map((d) =>
    typeof d === 'string'
      ? { name: d, active: true }
      : {
          name: d.name,
          active: Boolean(d.active),
          deletePending: Boolean(d.deletePending),
        }
  )
}
function openDocumentsFocus() {
  showDocumentsFocus.value = true
}
function handleKbDescriptionInput(event: Event) {
  emit('update:modelValue', {
    ...props.modelValue,
    kbDescription: (event.target as HTMLTextAreaElement).value,
  })
}
</script>

<style scoped></style>
