<template>
  <div class="step-container">
    <div v-if="loading" class="loading-wrapper flex-display-center">
      <span class="text-tip-2 text-primary-50-clor">加载中...</span>
    </div>
    <template v-else>
      <div class="content-wrapper">
        <ProposalInfoSection v-if="currentProposalInfo" :info="currentProposalInfo" />
        <FilterSection
          ref="filterSectionRef"
          :proposal-info="currentProposalInfo"
          :default-filters="defaultFilters"
        />
      </div>
      <ActionButtons
        show-set-as-current
        @reset="handleReset"
        @set-as-current="handleSetAsCurrent"
        @next="handleNext"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import type { ProposalInfo } from '../api'
import ProposalInfoSection from './ProposalInfoSection.vue'
import FilterSection from './FilterSection.vue'
import ActionButtons from './ActionButtons.vue'

const props = defineProps<{
  proposalInfo?: ProposalInfo | null
  defaultFilters?: Record<string, string[]>
}>()

const emit = defineEmits<{
  next: [selectedFilters: Record<string, string[]>]
}>()

// 提案信息（优先使用 props）
const currentProposalInfo = ref<ProposalInfo | null>(null)
// FilterSection 组件引用
const filterSectionRef = ref<InstanceType<typeof FilterSection> | null>(null)
// 加载状态
const loading = ref(true)
// 默认筛选条件
const defaultFilters = ref<Record<string, string[]>>({})

// 监听 props.proposalInfo 变化
watch(() => props.proposalInfo, (newInfo) => {
  if (newInfo) {
    currentProposalInfo.value = newInfo
    // 根据提案信息生成默认筛选条件（仅用于 Step1 内部状态跟踪，不再传给 FilterSection）
    defaultFilters.value = {
      policyArea: newInfo.defaultDomains?.length ? newInfo.defaultDomains : newInfo.areas,
      governmentType: newInfo.patternType ? [newInfo.patternType] : [],
      oppositionProposer: [],
      proposalTime: [],
    }
  }
  loading.value = false
}, { immediate: true })

// 重置所有筛选条件：清空所有已选项
function handleReset() {
  filterSectionRef.value?.reset()
}

// 设置为当前提案：恢复初始状态
function handleSetAsCurrent() {
  filterSectionRef.value?.setAsCurrent()
}

// 下一步：获取已选的筛选条件并传给父组件
function handleNext() {
  const selectedFilters = filterSectionRef.value?.getValues() || {}
  emit('next', selectedFilters)
}
</script>

<style scoped>
.step-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.loading-wrapper {
  flex: 1;
}

.content-wrapper {
  flex: 1;
  overflow: auto;
}
</style>
