<script setup lang="ts">
import { computed } from 'vue'

export type FilterSection =
  | {
      key: string
      title: string
      type: 'range'
      unit?: string
      minPlaceholder?: string
      maxPlaceholder?: string
    }
  | {
      key: string
      title: string
      type: 'chips'
      options: string[]
    }

type SelectedFilters = Record<string, string[]>
type RangeFilters = Record<string, { min: string; max: string }>
type RangePresets = Record<string, Array<{ label: string; min: string; max: string }>>

const props = defineProps<{
  show: boolean
  selectedFilters: SelectedFilters
  rangeFilters: RangeFilters
  sections: FilterSection[]
  rangePresets: RangePresets
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  'update:selectedFilters': [value: SelectedFilters]
  'update:rangeFilters': [value: RangeFilters]
}>()

const activeCount = computed(() => {
  const chipCount = Object.values(props.selectedFilters).reduce((sum, values) => sum + values.length, 0)
  const rangeCount = Object.values(props.rangeFilters).filter((range) => range.min || range.max).length
  return chipCount + rangeCount
})

function toggleChip(sectionKey: string, value: string) {
  const selected = props.selectedFilters[sectionKey] || []
  const next = selected.includes(value) ? selected.filter((item) => item !== value) : [...selected, value]
  emit('update:selectedFilters', { ...props.selectedFilters, [sectionKey]: next })
}

function updateRange(sectionKey: string, side: 'min' | 'max', value: string) {
  const current = props.rangeFilters[sectionKey] || { min: '', max: '' }
  emit('update:rangeFilters', {
    ...props.rangeFilters,
    [sectionKey]: { ...current, [side]: value },
  })
}

function applyRangePreset(sectionKey: string, min: string, max: string) {
  emit('update:rangeFilters', {
    ...props.rangeFilters,
    [sectionKey]: { min, max },
  })
}

function isRangePresetActive(sectionKey: string, min: string, max: string) {
  const range = props.rangeFilters[sectionKey]
  return range?.min === min && range?.max === max
}

function resetFilters() {
  emit('update:selectedFilters', {})
  emit('update:rangeFilters', {})
}
</script>

<template>
  <van-popup
    :show="show"
    position="bottom"
    round
    class="mobile-filter-sheet"
    @update:show="emit('update:show', $event)"
  >
    <header class="sheet-header">
      <strong>筛选</strong>
      <button type="button" @click="emit('update:show', false)">完成</button>
    </header>

    <div class="sheet-body">
      <section v-for="section in sections" :key="section.key" class="filter-section">
        <div class="filter-title">
          <h3>{{ section.title }}</h3>
          <span v-if="section.type === 'range' && section.unit">单位：{{ section.unit }}</span>
        </div>

        <template v-if="section.type === 'range'">
          <div class="range-row">
            <input
              :value="rangeFilters[section.key]?.min || ''"
              type="number"
              inputmode="decimal"
              :placeholder="section.minPlaceholder || '最低'"
              @input="updateRange(section.key, 'min', ($event.target as HTMLInputElement).value)"
            />
            <span></span>
            <input
              :value="rangeFilters[section.key]?.max || ''"
              type="number"
              inputmode="decimal"
              :placeholder="section.maxPlaceholder || '最高'"
              @input="updateRange(section.key, 'max', ($event.target as HTMLInputElement).value)"
            />
          </div>
          <div v-if="rangePresets[section.key]?.length" class="chip-grid">
            <button
              v-for="preset in rangePresets[section.key]"
              :key="`${section.key}-${preset.label}`"
              type="button"
              :class="{ active: isRangePresetActive(section.key, preset.min, preset.max) }"
              @click="applyRangePreset(section.key, preset.min, preset.max)"
            >
              {{ preset.label }}
            </button>
          </div>
        </template>

        <div v-else class="chip-grid">
          <button
            v-for="option in section.options"
            :key="`${section.key}-${option}`"
            type="button"
            :class="{ active: selectedFilters[section.key]?.includes(option) }"
            @click="toggleChip(section.key, option)"
          >
            {{ option }}
          </button>
        </div>
      </section>
    </div>

    <footer class="sheet-footer">
      <button type="button" @click="resetFilters">重置</button>
      <button type="button" class="primary" @click="emit('update:show', false)">
        查看结果{{ activeCount ? ` (${activeCount})` : '' }}
      </button>
    </footer>
  </van-popup>
</template>

<style scoped>
.mobile-filter-sheet {
  max-height: 86vh;
  overflow: hidden;
}

.sheet-header,
.sheet-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px;
  background: #fff;
}

.sheet-header {
  border-bottom: 1px solid #edf2f7;
}

.sheet-header strong {
  color: #17233d;
  font-size: 16px;
}

.sheet-header button,
.sheet-footer button {
  border: none;
  background: transparent;
  color: #2563eb;
  font-weight: 700;
}

.sheet-body {
  max-height: calc(86vh - 112px);
  overflow-y: auto;
  padding: 4px 16px 16px;
  background: #f7f8fa;
}

.filter-section {
  padding: 14px 0;
  border-bottom: 1px solid #e8edf3;
}

.filter-title {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 10px;
}

.filter-title h3 {
  margin: 0;
  color: #17233d;
  font-size: 14px;
}

.filter-title span {
  color: #8b9cb5;
  font-size: 12px;
}

.chip-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.chip-grid button {
  min-height: 32px;
  padding: 0 12px;
  border: 1px solid #dbe3ee;
  border-radius: 8px;
  background: #fff;
  color: #334155;
  font-size: 13px;
}

.chip-grid button.active {
  border-color: #2563eb;
  background: #eff6ff;
  color: #1d4ed8;
  font-weight: 700;
}

.range-row {
  display: grid;
  grid-template-columns: 1fr 18px 1fr;
  align-items: center;
  margin-bottom: 10px;
}

.range-row span {
  height: 1px;
  background: #cbd5e1;
}

.range-row input {
  min-width: 0;
  height: 36px;
  padding: 0 10px;
  border: 1px solid #dbe3ee;
  border-radius: 8px;
  background: #fff;
}

.sheet-footer {
  border-top: 1px solid #edf2f7;
}

.sheet-footer .primary {
  min-width: 128px;
  height: 38px;
  border-radius: 8px;
  background: #2563eb;
  color: #fff;
}
</style>
