<template>
  <a-modal
    v-model:open="dialogOpen"
    title="加入资料篮"
    width="720px"
    ok-text="确认"
    cancel-text="取消"
    @ok="handleConfirm"
  >
    <div class="import-dialog">
      <a-alert
        type="info"
        show-icon
        :message="title || `本次共选择 ${items.length} 项资料`"
        :description="description || '可只加入资料篮，也可直接导入到新建研究。'"

      />

      <a-card size="small" class="import-preview-card">
        <div class="preview-header">
          <span>待导入资料</span>
          <span>{{ items.length }} 项</span>
        </div>
        <a-list :data-source="items.slice(0, 5)" size="small">
          <template #renderItem="{ item }">
            <a-list-item>
              <div class="preview-item">
                <span class="preview-item__title">{{ item.title }}</span>
                <a-tag>{{ getItemTypeLabel(item.item_type) }}</a-tag>
              </div>
            </a-list-item>
          </template>
        </a-list>
        <div v-if="items.length > 5" class="preview-more">其余 {{ items.length - 5 }} 项将在确认后一并处理</div>
      </a-card>

      <a-form layout="vertical">
        <a-form-item label="导入目标">
          <a-radio-group v-model:value="target">
            <a-radio value="basket">仅加入资料篮</a-radio>
            <a-radio value="new">新建研究并导入</a-radio>
            <a-radio value="existing">导入到已有研究</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="target === 'existing'" label="选择研究记录">
          <a-select
            v-model:value="selectedRecordId"
            placeholder="请选择一个草稿或已规划的研究"
            show-search
            :filter-option="filterRecord"
            :loading="loadingRecords"
            style="width: 100%"
            @focus="loadExistingRecords"
          >
            <a-select-option v-for="r in existingRecords" :key="r.id" :value="r.id">
              <div style="display: flex; align-items: center; gap: 8px">
                <a-tag :color="r.status === 'draft' ? 'default' : 'blue'" :bordered="false" size="small">
                  {{ r.status === 'draft' ? '草稿' : '已规划' }}
                </a-tag>
                <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ r.title }}</span>
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="参考级别">
          <a-radio-group v-model:value="importance">
            <a-radio value="core">核心参考</a-radio>
            <a-radio value="reference">一般参考</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="备注">
          <a-textarea
            v-model:value="note"
            :auto-size="{ minRows: 2, maxRows: 4 }"
            placeholder="可填写导入原因、关注点或使用说明"
          />
        </a-form-item>

        <a-form-item v-if="extraOptions.length" label="附带策略">
          <a-checkbox-group v-model:value="selectedExtraKeys" class="extra-options">
            <div v-for="option in extraOptions" :key="option.key" class="extra-option-item">
              <a-checkbox :value="option.key">
                <div>
                  <div>{{ option.label }}</div>
                  <div v-if="option.description" class="extra-option-desc">{{ option.description }}</div>
                </div>
              </a-checkbox>
            </div>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { BasketItem, BasketImportance } from '@/types/basket'
import type {
  ImportDialogExtraOption,
  ResearchImportDialogPayload,
  ResearchImportTarget,
} from '@/types/research-import'
import { getItemTypeLabel } from '@/utils/basketKeys'

const props = withDefaults(defineProps<{
  open: boolean
  items: BasketItem[]
  title?: string
  description?: string
  extraOptions?: ImportDialogExtraOption[]
}>(), {
  title: '',
  description: '',
  extraOptions: () => [],
})

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'confirm', payload: ResearchImportDialogPayload): void
}>()

const target = ref<ResearchImportTarget>('new')
const importance = ref<BasketImportance>('reference')
const note = ref('')
const selectedExtraKeys = ref<string[]>([])
const selectedRecordId = ref<string | null>(null)
const existingRecords = ref<{ id: string; title: string; status: string }[]>([])
const loadingRecords = ref(false)

async function loadExistingRecords() {
  if (existingRecords.value.length > 0) return
  loadingRecords.value = true
  try {
    const { fetchRecordList } = await import('@/api/researchRecords')
    const res = await fetchRecordList({ status: 'draft', limit: 50 })
    const res2 = await fetchRecordList({ status: 'planned', limit: 50 })
    existingRecords.value = [...res.records, ...res2.records].map(r => ({
      id: r.id,
      title: r.title,
      status: r.status,
    }))
  } catch { /* ignore */ }
  finally { loadingRecords.value = false }
}

function filterRecord(input: string, option: any) {
  const record = existingRecords.value.find(r => r.id === option.value)
  return record?.title?.toLowerCase().includes(input.toLowerCase()) ?? false
}

const dialogOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value),
})

watch(
  () => props.open,
  (open) => {
    if (!open) return
    target.value = 'new'
    importance.value = 'reference'
    note.value = ''
    selectedExtraKeys.value = props.extraOptions
      .filter((option) => option.defaultChecked)
      .map((option) => option.key)
  },
  { immediate: true },
)

function handleConfirm() {
  emit('confirm', {
    target: target.value,
    importance: importance.value,
    note: note.value,
    selectedExtraKeys: [...selectedExtraKeys.value],
    existingRecordId: target.value === 'existing' ? selectedRecordId.value : undefined,
  })

  dialogOpen.value = false
}
</script>

<style scoped lang="less">
.import-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.import-preview-card {
  .preview-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-weight: 600;
  }
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.preview-item__title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.preview-more {
  margin-top: 8px;
  color: #8c8c8c;
  font-size: 12px;
}

.extra-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.extra-option-item {
  padding: 8px 12px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.extra-option-desc {
  margin-top: 2px;
  color: #8c8c8c;
  font-size: 12px;
}
</style>
