<template>
  <a-drawer
    :open="open"
    title="视图配置"
    placement="right"
    :width="520"
    @close="handleClose"
  >
    <a-tabs v-model:activeKey="activeTab">
      <!-- Filter tab -->
      <a-tab-pane key="filter" tab="筛选">
        <FilterBuilder
          ref="filterRef"
          :fields="fields"
          :model-value="currentFilters"
        />
        <div class="view-config-panel__actions">
          <a-button type="primary" @click="saveFilters">保存筛选</a-button>
        </div>
      </a-tab-pane>

      <!-- Sort tab -->
      <a-tab-pane key="sort" tab="排序">
        <div class="view-config-panel__sort-row">
          <a-select
            v-model:value="sortFieldId"
            placeholder="选择排序字段"
            style="width: 200px"
          >
            <a-select-option
              v-for="f in fields"
              :key="f.id"
              :value="f.id"
            >
              {{ f.name }}
            </a-select-option>
          </a-select>
          <a-select v-model:value="sortOrder" style="width: 100px">
            <a-select-option value="asc">升序</a-select-option>
            <a-select-option value="desc">降序</a-select-option>
          </a-select>
        </div>
        <div class="view-config-panel__actions">
          <a-button type="primary" @click="saveSort">保存排序</a-button>
        </div>
      </a-tab-pane>

      <!-- Hidden fields tab -->
      <a-tab-pane key="hidden" tab="隐藏字段">
        <p class="view-config-panel__hint">勾选要隐藏的字段：</p>
        <a-checkbox-group v-model:value="hiddenFieldIds">
          <div
            v-for="f in fields"
            :key="f.id"
            class="view-config-panel__field-check"
          >
            <a-checkbox :value="f.id">{{ f.name }}</a-checkbox>
          </div>
        </a-checkbox-group>
        <div class="view-config-panel__actions">
          <a-button type="primary" @click="saveHidden">保存隐藏配置</a-button>
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import {
  Drawer as ADrawer,
  Tabs as ATabs,
  Button as AButton,
  Select as ASelect,
  Checkbox as ACheckbox,
} from 'ant-design-vue'
import type { IBitableField, IBitableView } from '@/api/bitable'
import { useBitableStore } from '@/stores/bitable'
import FilterBuilder from './FilterBuilder.vue'

const props = defineProps<{
  open: boolean
  fields: IBitableField[]
  view: IBitableView | null
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

const store = useBitableStore()

const activeTab = ref('filter')
const filterRef = ref<InstanceType<typeof FilterBuilder> | null>(null)

// Current config from view
const currentFilters = computed(() => {
  const filters = props.view?.config?.filters as unknown
  if (!Array.isArray(filters)) return []
  return filters as { field_id: string; op: string; value: string | number | undefined }[]
})

const sortFieldId = ref<string>(
  (props.view?.config?.sort as { field?: string })?.field ?? '',
)
const sortOrder = ref<string>(
  (props.view?.config?.sort as { order?: string })?.order ?? 'asc',
)
const hiddenFieldIds = ref<string[]>(
  (props.view?.config?.hidden_fields as string[]) ?? [],
)

// Reset when view changes
watch(
  () => props.view?.id,
  () => {
    sortFieldId.value = (props.view?.config?.sort as { field?: string })?.field ?? ''
    sortOrder.value = (props.view?.config?.sort as { order?: string })?.order ?? 'asc'
    hiddenFieldIds.value = (props.view?.config?.hidden_fields as string[]) ?? []
  },
)

function handleClose(): void {
  emit('close')
}

async function saveFilters(): Promise<void> {
  if (!props.view) return
  const conditions = filterRef.value?.getConditions() ?? []
  const config = {
    ...props.view.config,
    filters: conditions,
  }
  await store.updateView(props.view.id, { config })
}

async function saveSort(): Promise<void> {
  if (!props.view) return
  const config = {
    ...props.view.config,
    sort: { field: sortFieldId.value, order: sortOrder.value },
  }
  await store.updateView(props.view.id, { config })
}

async function saveHidden(): Promise<void> {
  if (!props.view) return
  const config = {
    ...props.view.config,
    hidden_fields: hiddenFieldIds.value,
  }
  await store.updateView(props.view.id, { config })
}
</script>

<style scoped>
.view-config-panel__sort-row {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.view-config-panel__actions {
  margin-top: 16px;
}

.view-config-panel__hint {
  color: var(--text-secondary, #8c8c8c);
  margin-bottom: 12px;
}

.view-config-panel__field-check {
  margin-bottom: 8px;
}
</style>
