<script setup lang="ts">
import { ref } from 'vue';

import { ArrowLeft, EditPen } from '@element-plus/icons-vue';
import {
  ElButton,
  ElEmpty,
  ElIcon,
  ElInput,
  ElTable,
  ElTableColumn,
  ElTabPane,
  ElTabs,
} from 'element-plus';

import {
  formatJobStatus,
  formatJobType,
  formatRelationType,
} from '../composables/datacenter-constants';

const props = defineProps<{
  jobs: any[];
  loading: boolean;
  previewRows: any[];
  saveDescriptions: (payload: {
    fields?: Array<{ fieldDesc: string; fieldId: number | string }>;
    tableDesc?: string;
    tableId: number | string;
  }) => Promise<any>;
  schema: any;
  sourceUnavailable?: boolean;
  table: any;
}>();

const emit = defineEmits<{
  back: [];
}>();

const activeTab = ref('data');
const editingFieldId = ref<null | number | string>(null);
const editingFieldDesc = ref('');
const savingFieldId = ref<null | number | string>(null);

function startFieldEdit(field: any) {
  editingFieldId.value = field.id;
  editingFieldDesc.value = field.fieldDesc || '';
}

function cancelFieldEdit() {
  editingFieldId.value = null;
  editingFieldDesc.value = '';
}

async function saveFieldDescription(field: any) {
  const tableId = props.schema?.table?.id;
  if (!tableId || !field?.id || savingFieldId.value) return;
  savingFieldId.value = field.id;
  try {
    await props.saveDescriptions({
      tableDesc: props.schema?.table?.tableDesc || '',
      tableId,
      fields: [
        {
          fieldDesc: editingFieldDesc.value,
          fieldId: field.id,
        },
      ],
    });
    cancelFieldEdit();
  } finally {
    savingFieldId.value = null;
  }
}
</script>

<template>
  <div class="table-detail-view" v-loading="loading">
    <!-- 表头信息 -->
    <div class="detail-header">
      <div class="header-main">
        <button class="back-btn" @click="emit('back')">
          <ElIcon class="back-icon"><ArrowLeft /></ElIcon>
        </button>
        <div class="header-info">
          <h3 class="header-title">{{ table?.tableName }}</h3>
          <p v-if="schema?.table?.tableDesc" class="header-desc">
            {{ schema.table.tableDesc }}
          </p>
        </div>
      </div>
    </div>

    <!-- Tabs 内容 -->
    <ElTabs v-model="activeTab" class="detail-tabs">
      <ElTabPane label="数据信息" name="data">
        <div class="detail-scroll-region">
          <ElEmpty v-if="previewRows.length === 0" description="暂无数据" />
          <ElTable v-else :data="previewRows" size="small" class="flat-table">
            <ElTableColumn
              v-for="field in schema?.fields || []"
              :key="field.fieldName"
              :prop="field.fieldName"
              :label="field.fieldName"
              min-width="140"
            />
          </ElTable>
        </div>
      </ElTabPane>

      <ElTabPane label="字段结构" name="schema">
        <div class="detail-scroll-region">
          <ElTable :data="schema?.fields || []" size="small" class="flat-table">
            <ElTableColumn label="字段名" min-width="320">
              <template #default="{ row }">
                <div class="field-name-cell">
                  <span class="field-name-text">{{ row.fieldName }}</span>
                  <template v-if="editingFieldId === row.id">
                    <ElInput
                      v-model="editingFieldDesc"
                      size="small"
                      clearable
                      maxlength="200"
                      class="description-input"
                    />
                    <div class="inline-actions">
                      <ElButton
                        link
                        type="primary"
                        size="small"
                        :loading="savingFieldId === row.id"
                        @click="saveFieldDescription(row)"
                      >
                        保存
                      </ElButton>
                      <ElButton
                        link
                        size="small"
                        :disabled="savingFieldId === row.id"
                        @click="cancelFieldEdit"
                      >
                        取消
                      </ElButton>
                    </div>
                  </template>
                  <template v-else>
                    <span class="description-inline">{{
                      row.fieldDesc || ''
                    }}</span>
                    <ElButton
                      class="icon-action icon-action--edit"
                      link
                      size="small"
                      @click="startFieldEdit(row)"
                    >
                      <ElIcon><EditPen /></ElIcon>
                    </ElButton>
                  </template>
                </div>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="jdbcType" label="类型" width="120" />
          </ElTable>
        </div>
      </ElTabPane>

      <ElTabPane label="版本记录" name="version">
        <div class="detail-scroll-region">
          <div class="tag-flow">
            <ElTag
              v-for="version in schema?.versions || []"
              :key="version.id"
              effect="plain"
            >
              #{{ version.versionNo }}
              {{ version.versionLabel || '未命名版本' }}
            </ElTag>
          </div>
          <ElEmpty
            v-if="(schema?.versions || []).length === 0"
            description="暂无版本记录"
          />
        </div>
      </ElTabPane>

      <ElTabPane label="来源关系" name="lineage">
        <div class="detail-scroll-region">
          <div class="tag-flow">
            <ElTag
              v-for="item in schema?.upstreamLineage || []"
              :key="`up-${item.id}`"
              effect="plain"
              type="info"
            >
              上游 {{ formatRelationType(item.relationType) }} /
              {{ item.sourceTableId }}
            </ElTag>
            <ElTag
              v-for="item in schema?.downstreamLineage || []"
              :key="`down-${item.id}`"
              effect="plain"
              type="success"
            >
              下游 {{ formatRelationType(item.relationType) }} /
              {{ item.derivedTableId }}
            </ElTag>
          </div>
          <ElEmpty
            v-if="
              (schema?.upstreamLineage || []).length === 0 &&
              (schema?.downstreamLineage || []).length === 0
            "
            description="暂无来源关系"
          />
        </div>
      </ElTabPane>

      <ElTabPane label="处理记录" name="job">
        <div class="detail-scroll-region">
          <ElEmpty v-if="jobs.length === 0" description="暂无处理记录" />
          <ElTable v-else :data="jobs" size="small" class="flat-table">
            <ElTableColumn label="操作" width="120">
              <template #default="{ row }">
                {{ formatJobType(row.jobType) }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="状态" width="100">
              <template #default="{ row }">
                <ElTag
                  size="small"
                  :type="
                    row.status === 'SUCCESS'
                      ? 'success'
                      : row.status === 'FAILED'
                        ? 'danger'
                        : 'info'
                  "
                  effect="plain"
                >
                  {{ formatJobStatus(row.status) }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="created" label="时间" min-width="180" />
          </ElTable>
        </div>
      </ElTabPane>
    </ElTabs>
  </div>
</template>

<style scoped>
.table-detail-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 0 0 12px;
  background: transparent;
}

.detail-header {
  padding: 0 0 4px;
  margin-bottom: 10px;
}

.header-main {
  display: flex;
  gap: 12px;
  align-items: center;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  padding: 0;
  color: hsl(var(--text-muted));
  cursor: pointer;
  background: hsl(var(--surface-subtle) / 75%);
  border: 1px solid hsl(var(--border) / 70%);
  border-radius: 999px;
  transition: all 0.15s;
}

.back-btn:hover {
  color: hsl(var(--foreground));
  background: hsl(var(--accent));
}

.back-icon {
  width: 16px;
  height: 16px;
}

.header-info {
  min-width: 0;
}

.header-title {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 15px;
  font-weight: 600;
  color: hsl(var(--text-strong));
  white-space: nowrap;
}

.header-desc {
  margin: 4px 0 0;
  font-size: 13px;
  line-height: 1.5;
  color: hsl(var(--text-muted));
  overflow-wrap: anywhere;
}

.detail-tabs {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  padding: 0;
  background: transparent;
  box-shadow: none;
}

.detail-tabs :deep(.el-tabs__header) {
  padding: 0;
  margin: 0;
  border-bottom: 1px solid hsl(var(--border) / 42%);
}

.detail-tabs :deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}

.detail-tabs :deep(.el-tabs__content) {
  flex: 1;
  min-height: 0;
  padding: 0;
  overflow: hidden;
}

.detail-tabs :deep(.el-tab-pane) {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  padding: 12px 0 0;
}

.detail-scroll-region {
  flex: 1;
  min-height: 0;
  padding-right: 4px;
  overflow: auto;
}

.tag-flow {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.flat-table {
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: hsl(var(--surface-subtle) / 72%);
  --el-table-border-color: hsl(var(--table-row-border) / 70%);
  --el-table-current-row-bg-color: hsl(var(--table-row-hover));
  --el-fill-color-blank: transparent;

  overflow: hidden;
  border-radius: 0;
}

.field-name-cell {
  display: flex;
  gap: 8px;
  align-items: center;
  min-width: 0;
  min-height: 28px;
}

.field-name-text {
  flex-shrink: 0;
  color: hsl(var(--text-strong));
}

.description-inline {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  color: hsl(var(--text-muted));
  white-space: nowrap;
}

.description-input {
  width: min(320px, 100%);
}

.inline-actions {
  display: flex;
  flex-shrink: 0;
  gap: 4px;
  align-items: center;
}

.icon-action {
  min-width: auto;
  padding: 0 2px;
}

.icon-action :deep(.el-icon) {
  font-size: 15px;
}

.icon-action--edit {
  color: hsl(var(--primary));
}
</style>
