<template>
  <div class="cf-editor">
    <!-- Empty state (Open Question P2) -->
    <a-empty
      v-if="modelValue.length === 0"
      description="暂无规则（点击添加规则开始着色）"
    />

    <template v-else>
      <div
        v-for="(rule, idx) in modelValue"
        :key="idx"
        class="cf-editor__rule"
        :class="{ 'cf-editor__rule--disabled': !rule.enabled }"
      >
        <!-- Enable/disable toggle (left rail) -->
        <a-switch
          :checked="rule.enabled"
          size="small"
          @update:checked="onFieldChange(idx, { enabled: Boolean($event) })"
        />

        <!-- Field select -->
        <a-select
          :value="rule.field_id"
          size="small"
          placeholder="字段"
          style="width: 120px"
          @update:value="onFieldChange(idx, { field_id: String($event) })"
        >
          <a-select-option
            v-for="f in fields"
            :key="f.id"
            :value="f.id"
          >
            {{ f.name }}
          </a-select-option>
        </a-select>

        <!-- Operator select -->
        <a-select
          :value="rule.operator"
          size="small"
          placeholder="运算符"
          style="width: 100px"
          @update:value="onOperatorChange(idx, String($event))"
        >
          <a-select-option
            v-for="op in ALL_OPERATORS"
            :key="op"
            :value="op"
          >
            {{ OPERATOR_LABELS[op] }}
          </a-select-option>
        </a-select>

        <!-- Value input (hidden for is-empty) -->
        <a-input
          v-if="rule.operator !== 'is-empty'"
          :value="rule.value"
          size="small"
          :placeholder="valuePlaceholder(rule.operator)"
          style="width: 120px"
          @update:value="onFieldChange(idx, { value: String($event) })"
        />

        <!-- Color select (with swatch) -->
        <a-select
          :value="rule.color_key"
          size="small"
          style="width: 100px"
          @update:value="onColorChange(idx, String($event))"
        >
          <a-select-option
            v-for="ck in ALL_COLOR_KEYS"
            :key="ck"
            :value="ck"
          >
            <span class="cf-editor__color-option">
              <span
                class="cf-editor__color-swatch"
                :style="{ background: colorKeyToBgCssVar(ck), color: colorKeyToFgCssVar(ck) }"
              >
                A
              </span>
              <span>{{ COLOR_KEY_LABELS[ck] }}</span>
            </span>
          </a-select-option>
        </a-select>

        <!-- Bold toggle (WCAG 1.4.1 — default on) -->
        <a-tooltip title="同时加粗文本（WCAG 1.4.1 色盲可感知）">
          <a-button
            size="small"
            :type="rule.bold ? 'primary' : 'default'"
            :icon="h(BoldOutlined)"
            @click="onFieldChange(idx, { bold: !rule.bold })"
          />
        </a-tooltip>

        <!-- Delete rule -->
        <a-button
          size="small"
          danger
          :icon="h(DeleteOutlined)"
          @click="removeRule(idx)"
        />
      </div>
    </template>

    <!-- Add rule + color legend -->
    <div class="cf-editor__footer">
      <a-button
        size="small"
        type="dashed"
        :icon="h(PlusOutlined)"
        @click="addRule"
      >
        添加规则
      </a-button>
      <span class="cf-editor__legend">
        规则按顺序优先（首条匹配生效）
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { h } from 'vue'
import {
  Select as ASelect,
  Input as AInput,
  Button as AButton,
  Switch as ASwitch,
  Empty as AEmpty,
  Tooltip as ATooltip,
} from 'ant-design-vue'
import {
  PlusOutlined,
  DeleteOutlined,
  BoldOutlined,
} from '@ant-design/icons-vue'
import type { IBitableField } from '@/api/bitable'
import {
  ALL_COLOR_KEYS,
  ALL_OPERATORS,
  COLOR_KEY_LABELS,
  OPERATOR_LABELS,
  colorKeyToBgCssVar,
  colorKeyToFgCssVar,
  type ColorKey,
  type ConditionalFormatRule,
  type ConditionalOperator,
} from '@/helpers/groupingRulesUtils'

const props = defineProps<{
  modelValue: ConditionalFormatRule[]
  fields: IBitableField[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: ConditionalFormatRule[]): void
}>()

function emitUpdate(rules: ConditionalFormatRule[]): void {
  emit('update:modelValue', rules)
}

function addRule(): void {
  // Default new rule: equals / red / bold=true / enabled=true on first field.
  const firstField = props.fields[0]
  const newRule: ConditionalFormatRule = {
    field_id: firstField?.id ?? '',
    operator: 'equals',
    value: '',
    color_key: 'red',
    bold: true,
    enabled: true,
  }
  emitUpdate([...props.modelValue, newRule])
}

function removeRule(idx: number): void {
  emitUpdate(props.modelValue.filter((_, i) => i !== idx))
}

function onFieldChange(
  idx: number,
  patch: Partial<ConditionalFormatRule>,
): void {
  const next = props.modelValue.map((r, i) => (i === idx ? { ...r, ...patch } : r))
  emitUpdate(next)
}

function onOperatorChange(idx: number, op: string): void {
  // Cast through unknown because the select emits a generic string.
  const operator = op as ConditionalOperator
  onFieldChange(idx, { operator })
}

function onColorChange(idx: number, ck: string): void {
  const colorKey = ck as ColorKey
  onFieldChange(idx, { color_key: colorKey })
}

function valuePlaceholder(operator: ConditionalOperator): string {
  if (operator === 'between') return 'min,max'
  return '值'
}
</script>

<style scoped>
.cf-editor {
  display: flex;
  flex-direction: column;
  gap: var(--bitable-spacing-sm);
}

.cf-editor__rule {
  display: flex;
  align-items: center;
  gap: var(--bitable-spacing-xs);
  flex-wrap: wrap;
  padding: var(--bitable-spacing-xs) 0;
  border-bottom: 1px solid var(--bitable-color-border-split);
}

.cf-editor__rule--disabled {
  opacity: 0.55;
}

.cf-editor__color-option {
  display: inline-flex;
  align-items: center;
  gap: var(--bitable-spacing-xs);
}

.cf-editor__color-swatch {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: var(--bitable-radius-sm);
  font-weight: 700;
  font-size: var(--bitable-font-xs);
  /* Background + color set inline from tokens via colorKeyTo{Bg,Fg}CssVar */
}

.cf-editor__footer {
  display: flex;
  align-items: center;
  gap: var(--bitable-spacing-md);
  margin-top: var(--bitable-spacing-sm);
}

.cf-editor__legend {
  font-size: var(--bitable-font-xs);
  color: var(--bitable-color-text-tertiary);
}
</style>
