<template>
  <div class="view-switcher">
    <a-tabs
      v-model:activeKey="activeKey"
      type="editable-card"
      size="small"
      :add-icon="h(PlusOutlined)"
      @change="onSwitch"
      @edit="onEdit"
    >
      <a-tab-pane
        v-for="v in views"
        :key="v.id"
        :tab="v.name"
        :closable="false"
      />
    </a-tabs>

    <a-button
      v-if="activeKey"
      type="text"
      size="small"
      :icon="h(FilterOutlined)"
      @click="emit('config')"
    >
      配置
    </a-button>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, h } from 'vue'
import { Tabs as ATabs, Button as AButton } from 'ant-design-vue'
import { PlusOutlined, FilterOutlined } from '@ant-design/icons-vue'
import type { IBitableView } from '@/api/bitable'

const props = defineProps<{
  views: IBitableView[]
  activeViewId: string | null
}>()

const emit = defineEmits<{
  (e: 'switch', viewId: string): void
  (e: 'create'): void
  (e: 'config'): void
}>()

// antd Tabs activeKey is string | number | undefined; bridge to/from null
const activeKey = ref<string | undefined>(props.activeViewId ?? undefined)

watch(
  () => props.activeViewId,
  (val) => {
    activeKey.value = val ?? undefined
  },
)

function onSwitch(key: string | number): void {
  emit('switch', String(key))
}

function onEdit(_targetKey: unknown, action: 'add' | 'remove'): void {
  if (action === 'add') {
    emit('create')
  }
  // remove is disabled (closable=false) — no-op
}
</script>

<style scoped>
.view-switcher {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  border-bottom: 1px solid var(--border-color, #f0f0f0);
}

.view-switcher :deep(.ant-tabs) {
  flex: 1;
  min-width: 0;
}
</style>
