<template>
  <span
    @click="selectMode && _doc.active ? $emit('toggle-selection', _doc.name) : null"
    class="inline-flex items-center space-x-1 px-3 py-1 border rounded-md text-sm select-none transition group"
    :class="[
      selectMode && _doc.active ? 'cursor-pointer' : '',
      selectedDocs.has(_doc.name) ? 'bg-indigo-50 border-indigo-400' : 'bg-white border-primary',
      !_doc.active
        ? indexingStatus === 'failure'
          ? '!border-red-400 !bg-red-50'
          : '!border-border'
        : selectMode
        ? 'hover:border-indigo-300'
        : 'hover:border-gray-400',
    ]"
  >
    <!-- Checkbox in select mode -->
    <input
      v-if="selectMode && _doc.active"
      type="checkbox"
      :checked="selectedDocs.has(_doc.name)"
      @click.stop="$emit('toggle-selection', _doc.name)"
      class="w-3 h-3 rounded border-gray-300 text-indigo-600 focus:ring-0"
    />

    <!-- File type icon -->
    <i v-if="getFileIcon(_doc.name)" :class="getFileIcon(_doc.name)" class="mr-1 text-gray-500"></i>

    <span
      class="truncate max-w-[120px]"
      :title="_doc.name"
      :class="{ 'text-red-600': !_doc.active && indexingStatus === 'failure' }"
    >
      {{ _doc.name }}
    </span>

    <!-- Loading indicator -->
    <Loader2 v-if="!_doc.active && indexingBusy" class="animate-spin w-4 h-4 text-gray-400" />

    <!-- Success indicator -->
    <Check v-if="_doc.active" class="w-4 h-4 text-primary"></Check>

    <!-- Failure indicator -->
    <AlertCircle
      v-if="!_doc.active && indexingStatus === 'failure' && !indexingBusy"
      class="w-4 h-4 text-red-500"
      title="Indexing failed"
    />

    <button
      v-if="!indexingBusy && !selectMode"
      @click="$emit('delete', _doc.name)"
      class="ml-1 p-0.5 text-foreground hover:text-gray-400 transition-colors"
      :disabled="indexingBusy"
    >
      <X class="w-4 h-4" />
    </button>
  </span>
</template>

<script setup lang="ts">
import { Check, Loader2, X, AlertCircle } from 'lucide-vue-next'
import type { DocEntry } from '@/store/agentStore'
import { computed } from 'vue'
// Props
const props = defineProps<{
  doc: DocEntry
  selectMode: boolean
  selectedDocs: Set<string>
  indexingBusy: boolean
  indexingStatus?: string
}>()
const _doc = computed(() => {
  if (props.doc instanceof File) {
    return {
      name: props.doc.name,
      active: false,
      deletePending: false,
    }
  }
  return props.doc
})
// Emits
defineEmits<{
  (e: 'toggle-selection', docName: string): void
  (e: 'delete', docName: string): void
}>()

// Get file type icon based on file extension
function getFileIcon(filename: string): string | null {
  const extension = filename.toLowerCase().split('.').pop()
  switch (extension) {
    case 'pdf':
      return 'dku-icon-file-12'
    case 'jpg':
    case 'jpeg':
    case 'png':
      return 'dku-icon-image-12'
    case 'txt':
      return 'dku-icon-file-text-12'
    default:
      return null
  }
}
</script>
