<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { ElPopover } from 'element-plus'
import { computed } from 'vue'

interface SkinGroup {
  key: string
  title: string
  options: string[]
}

interface Props {
  skinGroup: string
  skinName: string
  groups: SkinGroup[]
  popoverProps: Record<string, any>
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:skinGroup': [value: string]
  'update:skinName': [value: string]
  close: []
}>()

const isActive = computed(() => {
  return !!props.skinGroup || !!props.skinName
})

const chipLabel = computed(() => {
  if (props.skinName) return props.skinName
  if (props.skinGroup) {
    return props.groups.find((g) => g.key === props.skinGroup)?.title || '皮肤'
  }
  return '皮肤'
})

function selectSkin(group: string, name = '') {
  emit('update:skinGroup', group)
  emit('update:skinName', name)
  emit('close')
}

function resetSkin() {
  emit('update:skinGroup', '')
  emit('update:skinName', '')
  emit('close')
}
</script>

<template>
  <el-popover v-bind="popoverProps" :width="320">
    <template #reference>
      <button class="filter-chip" :class="{ active: isActive }" type="button">
        <span>{{ chipLabel }}</span>
        <el-icon><ArrowDown /></el-icon>
      </button>
    </template>
    <div class="skin-filter-menu">
      <button
        class="skin-reset"
        type="button"
        :class="{ active: !skinGroup && !skinName }"
        @click="resetSkin"
      >
        全部皮肤
      </button>
      <div v-for="group in groups" :key="group.key" class="skin-filter-group">
        <div class="skin-filter-title">
          <strong>{{ group.title }}</strong>
          <button
            type="button"
            :class="{ active: skinGroup === group.key && !skinName }"
            @click="selectSkin(group.key)"
          >
            全部{{ group.title.replace('干员', '') }}
          </button>
        </div>
        <div class="skin-filter-options">
          <button
            v-for="skin in group.options"
            :key="skin"
            type="button"
            :class="{ active: skinGroup === group.key && skinName === skin }"
            @click="selectSkin(group.key, skin)"
          >
            {{ skin }}
          </button>
        </div>
      </div>
    </div>
  </el-popover>
</template>

<style src="@/styles/home-filters.css"></style>
