<template>
  <div class="dataset-manage">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-left">
        <h2>数据集管理</h2>
        <p class="header-desc">创建和管理训练数据集</p>
      </div>
      <el-button type="primary" @click="showCreateDialog = true" class="create-btn">
        <el-icon><Plus /></el-icon>
        新建数据集
      </el-button>
    </div>

    <!-- Tabs -->
    <el-tabs v-model="activeTab" class="dataset-tabs">
      <el-tab-pane label="训练数据集" name="train">
        <div class="dataset-list" v-loading="loading">
          <div v-if="!loading && datasets.length === 0" class="empty-state">
            <el-icon size="48"><Collection /></el-icon>
            <h3>暂无数据集</h3>
            <p>创建您的第一个数据集开始使用</p>
            <el-button type="primary" @click="showCreateDialog = true">新建数据集</el-button>
          </div>

          <div v-else class="datasets-grid">
            <div
              v-for="(dataset, index) in datasets"
              :key="dataset.id"
              class="dataset-card"
              :style="{ '--delay': index * 0.08 + 's' }"
            >
              <div class="dataset-header">
                <div class="dataset-icon">
                  <el-icon size="28"><Collection /></el-icon>
                </div>
                <el-dropdown trigger="click">
                  <el-button text size="small" class="menu-btn">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleExport(dataset)">导出</el-dropdown-item>
                      <el-dropdown-item @click="handleDuplicate(dataset)">复制</el-dropdown-item>
                      <el-dropdown-item divided @click="handleDelete(dataset)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <h3 class="dataset-name">{{ dataset.name }}</h3>
              <p class="dataset-desc">{{ dataset.description || '暂无描述' }}</p>
              <div class="dataset-meta">
                <el-tag size="small" effect="dark">{{ getTypeName(dataset.dataset_type) }}</el-tag>
                <span class="meta-count">{{ dataset.question_count || 0 }} 条</span>
              </div>
              <div class="dataset-footer">
                <span class="meta-date">{{ formatDate(dataset.created_at) }}</span>
                <el-button type="primary" size="small" @click="handleExport(dataset)">
                  导出
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="图片数据集" name="image">
        <div class="empty-state">
          <el-icon size="48"><Picture /></el-icon>
          <h3>即将上线</h3>
          <p>图片数据集功能正在开发中</p>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- Create Dialog -->
    <el-dialog v-model="showCreateDialog" title="新建数据集" width="520px" class="create-dialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
        <el-form-item label="数据集名称" prop="name">
          <el-input v-model="form.name" placeholder="输入数据集名称" size="large" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="可选描述" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="数据集类型">
          <el-radio-group v-model="form.dataset_type">
            <el-radio-button label="qa">问答对</el-radio-button>
            <el-radio-button label="conversation">多轮对话</el-radio-button>
            <el-radio-button label="instruction">指令跟随</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="creating">创建</el-button>
      </template>
    </el-dialog>

    <!-- Export Dialog -->
    <el-dialog v-model="showExportDialog" title="导出数据集" width="480px" class="export-dialog">
      <div class="export-options">
        <div
          v-for="option in exportOptions"
          :key="option.value"
          class="export-option"
          :class="{ active: exportFormat === option.value }"
          @click="exportFormat = option.value"
        >
          <div class="option-icon" :style="{ background: option.color }">
            <el-icon size="20"><component :is="option.icon" /></el-icon>
          </div>
          <div class="option-info">
            <span class="option-name">{{ option.label }}</span>
            <span class="option-desc">{{ option.desc }}</span>
          </div>
          <el-icon v-if="exportFormat === option.value" class="check-icon"><CircleCheck /></el-icon>
        </div>
      </div>
      <template #footer>
        <el-button @click="showExportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmExport">导出</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { datasetApi } from '@/api'

const route = useRoute()
const projectId = computed(() => route.params.id)

const loading = ref(false)
const creating = ref(false)
const datasets = ref([])
const activeTab = ref('train')
const showCreateDialog = ref(false)
const showExportDialog = ref(false)
const selectedDataset = ref(null)
const exportFormat = ref('alpaca')

const form = reactive({
  name: '',
  description: '',
  dataset_type: 'qa'
})

const rules = {
  name: [{ required: true, message: '请输入数据集名称', trigger: 'blur' }]
}

const exportOptions = [
  { value: 'alpaca', label: 'Alpaca', desc: 'Alpaca 格式', icon: 'Document', color: '#6366f1' },
  { value: 'sharegpt', label: 'ShareGPT', desc: 'ShareGPT 格式', icon: 'ChatDotSquare', color: '#10b981' },
  { value: 'llama_factory', label: 'LLaMA Factory', desc: 'LLaMA Factory 格式', icon: 'Setting', color: '#f59e0b' },
  { value: 'json', label: 'JSON', desc: '原生 JSON 格式', icon: 'List', color: '#3b82f6' }
]

const fetchDatasets = async () => {
  loading.value = true
  try {
    const res = await datasetApi.list(projectId.value)
    datasets.value = res.data.datasets || []
  } catch (error) {
    datasets.value = []
  } finally {
    loading.value = false
  }
}

const handleCreate = async () => {
  creating.value = true
  try {
    await datasetApi.create(projectId.value, form)
    ElMessage.success('创建成功')
    showCreateDialog.value = false
    fetchDatasets()
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

const handleExport = (dataset) => {
  selectedDataset.value = dataset
  exportFormat.value = 'alpaca'
  showExportDialog.value = true
}

const confirmExport = async () => {
  try {
    const res = await datasetApi.export(projectId.value, selectedDataset.value.id, { format: exportFormat.value })
    const blob = new Blob([JSON.stringify(res.data || res, null, 2)], { type: 'application/json' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${selectedDataset.value.name}.${exportFormat.value === 'alpaca' ? 'json' : exportFormat.value}`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
    showExportDialog.value = false
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleDuplicate = (dataset) => {
  ElMessage.info('复制功能开发中')
}

const handleDelete = async (dataset) => {
  try {
    await ElMessageBox.confirm('确定删除此数据集？', '确认', { type: 'warning' })
    await datasetApi.delete(projectId.value, dataset.id)
    ElMessage.success('删除成功')
    fetchDatasets()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}

const getTypeName = (type) => {
  const map = { qa: '问答对', conversation: '多轮对话', instruction: '指令' }
  return map[type] || type
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getMonth() + 1}/${d.getDate()}`
}

onMounted(() => fetchDatasets())
</script>

<style scoped>
.dataset-manage {
  padding: 32px;
  max-width: 1200px;
}

/* Header */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
}

.header-left h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.header-desc {
  font-size: 14px;
  color: var(--text-tertiary);
}

.create-btn {
  padding: 10px 20px;
  font-weight: 500;
  border-radius: var(--radius-md);
}

/* Tabs */
.dataset-tabs {
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  padding: 20px;
}

/* Dataset Grid */
.datasets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.dataset-card {
  background: var(--bg-tertiary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  padding: 20px;
  transition: all var(--transition-base);
  animation: cardIn 0.4s ease backwards;
  animation-delay: var(--delay);
}

@keyframes cardIn {
  from {
    opacity: 0;
    transform: translateY(15px);
  }
}

.dataset-card:hover {
  border-color: var(--accent-primary);
  transform: translateY(-3px);
}

.dataset-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.dataset-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-primary-muted);
  border-radius: var(--radius-md);
  color: var(--accent-primary);
}

.menu-btn {
  color: var(--text-muted);
}

.dataset-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.dataset-desc {
  font-size: 13px;
  color: var(--text-tertiary);
  margin-bottom: 16px;
  line-height: 1.5;
}

.dataset-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.meta-count {
  font-size: 13px;
  color: var(--text-muted);
}

.dataset-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 14px;
  border-top: 1px solid var(--border-subtle);
}

.meta-date {
  font-size: 12px;
  color: var(--text-muted);
}

/* Empty State */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-state .el-icon {
  color: var(--text-muted);
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 18px;
  margin-bottom: 8px;
}

.empty-state p {
  color: var(--text-tertiary);
  margin-bottom: 20px;
}

/* Export Options */
.export-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.export-option {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.export-option:hover {
  border-color: var(--border-default);
}

.export-option.active {
  border-color: var(--accent-primary);
  background: var(--accent-primary-muted);
}

.option-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  color: white;
}

.option-info {
  flex: 1;
}

.option-name {
  font-weight: 600;
  display: block;
  margin-bottom: 2px;
}

.option-desc {
  font-size: 12px;
  color: var(--text-muted);
}

.check-icon {
  color: var(--accent-primary);
}
</style>
