<template>
  <a-modal
    :open="open"
    title="分段预览"
    :width="720"
    :footer="null"
    :destroy-on-close="true"
    @update:open="handleOpenChange"
  >
    <div class="segment-preview">
      <!-- File picker + params -->
      <a-space direction="vertical" :size="12" style="width: 100%">
        <a-upload-dragger
          :multiple="false"
          :show-upload-list="false"
          :before-upload="handleFileSelect"
          accept=".pdf,.docx,.doc,.md,.txt,.html,.csv,.json"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">
            {{ selectedFile ? selectedFile.name : '点击或拖拽文件到此区域' }}
          </p>
          <p class="ant-upload-hint">选择文件预览分段效果（不会保存或向量化）</p>
        </a-upload-dragger>

        <a-form layout="inline" class="preview-form">
          <a-form-item label="分块大小">
            <a-input-number
              v-model:value="chunkSize"
              :min="64"
              :max="4096"
              :step="64"
              style="width: 110px"
            />
          </a-form-item>
          <a-form-item label="重叠">
            <a-input-number
              v-model:value="chunkOverlap"
              :min="0"
              :max="512"
              :step="10"
              style="width: 100px"
            />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              :loading="kbStore.isPreviewing"
              :disabled="!selectedFile"
              @click="handlePreview"
            >
              生成预览
            </a-button>
          </a-form-item>
        </a-form>
      </a-space>

      <!-- Results -->
      <div v-if="kbStore.previewResult" class="preview-results">
        <a-divider>
          分段结果 ({{ kbStore.previewResult.total_chunks }} 块)
        </a-divider>
        <a-list
          :data-source="kbStore.previewResult.chunks"
          size="small"
          :pagination="kbStore.previewResult.total_chunks > 10
            ? { pageSize: 10, size: 'small' }
            : false"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #title>
                  <span class="chunk-index">#{{ item.index }}</span>
                </template>
                <template #description>
                  <div class="chunk-content">{{ item.content }}</div>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <a-empty
        v-else-if="!kbStore.isPreviewing"
        description="选择文件并点击「生成预览」查看分段结果"
      />
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { useKnowledgeStore } from '@/stores/knowledge'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const kbStore = useKnowledgeStore()

const selectedFile = ref<File | null>(null)
const chunkSize = ref(512)
const chunkOverlap = ref(50)

function handleOpenChange(value: boolean): void {
  emit('update:open', value)
  if (!value) {
    // Reset state when closing
    selectedFile.value = null
    chunkSize.value = 512
    chunkOverlap.value = 50
    kbStore.clearPreview()
  }
}

function handleFileSelect(file: File): false {
  selectedFile.value = file
  return false
}

async function handlePreview(): Promise<void> {
  if (!selectedFile.value) {
    message.warning('请先选择文件')
    return
  }
  try {
    const result = await kbStore.previewDocument(
      selectedFile.value,
      chunkSize.value,
      chunkOverlap.value,
    )
    message.success(`已生成 ${result.total_chunks} 个分段`)
  } catch (err) {
    const detail = err instanceof Error ? err.message : '分段预览失败'
    message.error(detail)
  }
}

// Reset when reopened
watch(
  () => props.open,
  (val) => {
    if (val) {
      selectedFile.value = null
      kbStore.clearPreview()
    }
  },
)
</script>

<style scoped>
.segment-preview {
  padding: 4px 0;
}

.preview-form {
  flex-wrap: wrap;
  gap: 8px;
}

.preview-results {
  margin-top: 8px;
}

.chunk-index {
  font-weight: 600;
  color: var(--color-primary);
}

.chunk-content {
  font-size: 13px;
  line-height: 1.6;
  color: var(--text-primary);
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 160px;
  overflow-y: auto;
}
</style>
