<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择变量"
    width="720px"
    append-to-body
    :close-on-click-modal="false"
  >
    <div class="variable-selector">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索变量名称或类型..."
        prefix-icon="Search"
        clearable
        style="margin-bottom: 16px"
      />

      <el-scrollbar max-height="420px">
        <div v-if="filteredVariableGroups.length === 0" class="empty-tip">
          <el-empty description="暂无可用变量" />
        </div>

        <div v-for="group in filteredVariableGroups" :key="group.id" class="variable-group">
          <div class="group-title">{{ group.name }}</div>
          <el-table
            :data="group.variables"
            size="small"
            border
            highlight-current-row
            :row-class-name="getRowClassName"
            @row-click="handleSelectVariable"
          >
            <el-table-column width="52" align="center">
              <template #default="{ row }">
                <el-radio v-model="selectedVarId" :value="row.id" @click.stop />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="变量名" min-width="180" show-overflow-tooltip />
            <el-table-column label="值" min-width="180" show-overflow-tooltip>
              <template #default="{ row }">
                {{ formatValue(row.value) }}
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="120" show-overflow-tooltip />
          </el-table>
        </div>
      </el-scrollbar>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-name">当前选中：{{ selectedVariableName || '未选择' }}</span>
        <div>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :disabled="!selectedVariable">
            确定
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { Variable, VariableGroup, VariableType } from '@/types/variables'

const props = defineProps<{
  modelValue: boolean
  allVariables: VariableGroup[]
  currentVarId?: string
  supportType?: VariableType
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: [varId: string, source: 'page' | 'global']
  cancel: []
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const searchKeyword = ref('')
const selectedVarId = ref<string>('')

const sortedVariableGroups = computed(() => {
  return [...props.allVariables].sort((a, b) => {
    if (a.id === 'page-vars') return -1
    if (b.id === 'page-vars') return 1
    return 0
  })
})

const filteredVariableGroups = computed(() => {
  const keyword = searchKeyword.value.toLowerCase()
  return sortedVariableGroups.value
    .map((group) => ({
      ...group,
      variables: group.variables.filter((v) => {
        const matchType = !props.supportType || v.type === props.supportType
        const matchKeyword =
          !keyword ||
          v.name.toLowerCase().includes(keyword) ||
          v.type.toLowerCase().includes(keyword) ||
          String(v.value ?? '')
            .toLowerCase()
            .includes(keyword)

        return matchType && matchKeyword
      })
    }))
    .filter((group) => group.variables.length > 0)
})

const selectedVariable = computed<Variable | undefined>(() => {
  if (!selectedVarId.value) return undefined

  for (const group of filteredVariableGroups.value) {
    const variable = group.variables.find((item) => item.id === selectedVarId.value)
    if (variable) return variable
  }

  return undefined
})

const selectedVariableSource = computed<'page' | 'global' | ''>(() => {
  if (!selectedVarId.value) return ''
  for (const group of filteredVariableGroups.value) {
    if (group.variables.some((item) => item.id === selectedVarId.value)) {
      return group.id === 'page-vars' ? 'page' : 'global'
    }
  }
  return ''
})

const selectedVariableName = computed(() => selectedVariable.value?.name || '')

const formatValue = (value: any): string => {
  if (value === undefined || value === null) return 'null'
  if (typeof value === 'string') {
    const truncated = value.length > 40 ? value.substring(0, 40) + '...' : value
    return `"${truncated}"`
  }
  if (typeof value === 'object') return JSON.stringify(value)
  return String(value)
}

const handleSelectVariable = (variable: Variable) => {
  selectedVarId.value = variable.id
}

const getRowClassName = ({ row }: { row: Variable }) => {
  return row.id === selectedVarId.value ? 'is-selected-row' : ''
}

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      selectedVarId.value = props.currentVarId || ''
      searchKeyword.value = ''
    }
  }
)

watch(filteredVariableGroups, () => {
  if (!selectedVarId.value) return
  if (!selectedVariable.value) {
    selectedVarId.value = ''
  }
})

const handleConfirm = () => {
  if (selectedVariable.value && selectedVariableSource.value) {
    emit('confirm', selectedVarId.value, selectedVariableSource.value)
    dialogVisible.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
  dialogVisible.value = false
}
</script>

<style scoped lang="less">
.variable-selector {
  .empty-tip {
    text-align: center;
    padding: 40px 0;
  }

  .variable-group {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    .group-title {
      font-weight: 600;
      color: var(--text-primary);
      margin-bottom: 12px;
      padding-left: 4px;
      font-size: 14px;
    }

    :deep(.el-table__row) {
      cursor: pointer;
    }

    :deep(.is-selected-row) {
      --el-table-tr-bg-color: var(--el-color-primary-light-9);
    }

    :deep(.el-radio) {
      height: 20px;

      .el-radio__label {
        display: none;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  width: 100%;

  .selected-name {
    font-size: 12px;
    min-width: 0;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
