<script setup lang="ts">
import { computed } from 'vue'
import type { DatasetVersion } from '@/types'

const props = defineProps<{
  modelValue: string
  versions: DatasetVersion[]
  viewedVersion?: DatasetVersion
  activeVersionId: string
  isViewingActiveVersion: boolean
  hasPendingVersionChanges: boolean
  versionLoading: boolean
  savingRecord: boolean
  activatingVersion: boolean
  deletingVersion: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
  change: [versionId: string]
  activate: []
  delete: []
}>()

type VersionAction = 'activate' | 'delete'

const actionsDisabled = computed(
  () =>
    props.versionLoading ||
    props.savingRecord ||
    props.activatingVersion ||
    props.deletingVersion,
)

const deleteDisabledReason = computed(() => {
  if (props.viewedVersion?.version === 1) return '初始版本不可删除'
  if (props.versions.length <= 1) return '至少需要保留一个版本'
  return ''
})

const deleteDisabled = computed(
  () => actionsDisabled.value || Boolean(deleteDisabledReason.value),
)

function formatVersionTime(value: string) {
  return new Date(value).toLocaleString('zh-CN', { hour12: false })
}

function versionOptionLabel(version: DatasetVersion) {
  const status = version.id === props.activeVersionId ? '当前版本' : '历史版本'
  return `V${version.version} · ${status} · ${formatVersionTime(version.create_time)}`
}

function handleVersionChange(versionId: string) {
  emit('update:modelValue', versionId)
  emit('change', versionId)
}

function handleVersionAction(command: VersionAction) {
  if (actionsDisabled.value) return
  if (command === 'activate') {
    emit('activate')
    return
  }
  if (deleteDisabled.value) return
  emit('delete')
}
</script>

<template>
  <section class="version-control-bar" aria-label="数据集版本控制">
    <div class="version-selector-group">
      <label for="dataset-version-select">数据版本</label>
      <el-select
        id="dataset-version-select"
        :model-value="modelValue"
        class="version-select"
        :loading="versionLoading"
        :disabled="versionLoading || savingRecord"
        aria-label="选择要查看的数据集版本"
        @change="handleVersionChange"
      >
        <el-option
          v-for="version in versions"
          :key="version.id"
          :label="versionOptionLabel(version)"
          :value="version.id"
        />
      </el-select>
    </div>

    <div class="version-status" role="status" aria-live="polite">
      <template v-if="viewedVersion">
        <el-tag v-if="isViewingActiveVersion" type="success">
          V{{ viewedVersion.version }} · 当前版本
        </el-tag>
        <el-tag v-else type="info">V{{ viewedVersion.version }} · 历史版本（只读）</el-tag>
        <el-tag v-if="hasPendingVersionChanges" type="warning">有待保存修改</el-tag>
        <span>
          {{ viewedVersion.description || '无版本说明' }} ·
          {{ formatVersionTime(viewedVersion.create_time) }}
        </span>
      </template>
    </div>

    <el-dropdown
      v-if="viewedVersion && !isViewingActiveVersion"
      class="version-actions"
      trigger="click"
      placement="bottom-end"
      popper-class="version-actions-popper"
      :disabled="actionsDisabled"
      @command="handleVersionAction"
    >
      <el-button
        class="version-actions-button"
        :loading="activatingVersion || deletingVersion"
        :disabled="actionsDisabled"
        aria-label="打开历史版本操作菜单"
      >
        <i
          v-if="!activatingVersion && !deletingVersion"
          class="fa fa-ellipsis-h"
          aria-hidden="true"
        />
      </el-button>

      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            command="activate"
            class="version-action-primary"
            :disabled="actionsDisabled"
          >
            <i class="fa fa-check-circle" aria-hidden="true" />
            设为当前版本
          </el-dropdown-item>
          <el-dropdown-item
            command="delete"
            class="version-action-danger"
            :disabled="deleteDisabled"
            :title="deleteDisabledReason || undefined"
            divided
          >
            <i class="fa fa-trash-o" aria-hidden="true" />
            删除版本
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </section>
</template>

<style scoped lang="scss">
.version-control-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  min-height: 64px;
  margin-bottom: 12px;
  padding: 10px 14px;
  box-sizing: border-box;
  border: 1px solid #dfe5ee;
  border-radius: 10px;
  background: #fff;
}

.version-selector-group {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 0 auto;
}

.version-selector-group label {
  color: #344054;
  font-size: 13px;
  font-weight: 600;
}

.version-select {
  width: 300px;
}

.version-status {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 10px;
  min-width: 0;
}

.version-status > span {
  overflow: hidden;
  color: #7c8799;
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.version-actions {
  flex: 0 0 auto;
  line-height: 1;
}

.version-actions-button {
  width: 40px;
  height: 40px;
  flex: 0 0 auto;
  padding: 0;
  border-radius: 10px;
}

.version-actions-button i {
  font-size: 16px;
}

:global(.version-actions-popper .el-dropdown-menu__item) {
  gap: 8px;
  min-height: 40px;
}

:global(.version-actions-popper .el-dropdown-menu) {
  min-width: 168px;
}

:global(.version-actions-popper .version-action-primary:not(.is-disabled) i) {
  color: var(--primary-color);
}

:global(.version-actions-popper .version-action-danger:not(.is-disabled)) {
  color: var(--el-color-danger);
}

:global(.version-actions-popper .version-action-danger:not(.is-disabled):hover) {
  color: var(--el-color-danger);
  background: var(--el-color-danger-light-9);
}

@media (max-width: 680px) {
  .version-control-bar,
  .version-selector-group,
  .version-status {
    align-items: stretch;
    flex-direction: column;
  }

  .version-select,
  .version-selector-group {
    width: 100%;
  }

  .version-status {
    width: 100%;
    min-width: 0;
  }

  .version-status > span {
    white-space: normal;
    overflow-wrap: anywhere;
  }

  .version-actions {
    align-self: flex-end;
  }
}
</style>
