<script setup lang="ts">
import type { MemberTierListItemDto } from '#/api/member';

import { IconifyIcon } from '@vben/icons';

import { Button, Empty, Spin, Tag } from 'ant-design-vue';

import { resolveTierIcon } from '../composables/member-page/helpers';

interface Props {
  canManage: boolean;
  loading: boolean;
  tiers: MemberTierListItemDto[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'create'): void;
  (event: 'delete', tierId: string): void;
  (event: 'edit', tierId: string): void;
}>();
</script>

<template>
  <div class="mm-tier-system">
    <div class="mm-section-title">会员等级</div>

    <Spin :spinning="props.loading">
      <template v-if="props.tiers.length > 0">
        <div class="mm-tier-list">
          <div
            v-for="tier in props.tiers"
            :key="tier.tierId"
            class="mm-tier-card"
          >
            <div class="mm-tier-order">{{ tier.sortOrder }}</div>
            <div
              class="mm-tier-icon"
              :style="{
                color: tier.colorHex,
                background: 'rgba(0,0,0,0.03)',
              }"
            >
              <IconifyIcon :icon="resolveTierIcon(tier.iconKey)" />
            </div>

            <div class="mm-tier-main">
              <div class="mm-tier-name-row">
                <span class="mm-tier-name" :style="{ color: tier.colorHex }">
                  {{ tier.name }}
                </span>
                <Tag v-if="tier.isDefault" color="blue">默认</Tag>
              </div>
              <div class="mm-tier-condition">{{ tier.conditionText }}</div>
              <div class="mm-tier-perks">
                <Tag
                  v-for="perk in tier.perks"
                  :key="`${tier.tierId}-${perk}`"
                  class="mm-tier-perk"
                >
                  {{ perk }}
                </Tag>
              </div>
            </div>

            <div class="mm-tier-side">
              <div class="mm-tier-count">{{ tier.memberCount }} 人</div>
              <div class="mm-tier-actions">
                <Button
                  size="small"
                  :disabled="!props.canManage"
                  @click="emit('edit', tier.tierId)"
                >
                  编辑
                </Button>
                <Button
                  size="small"
                  danger
                  :disabled="!props.canManage || !tier.canDelete"
                  @click="emit('delete', tier.tierId)"
                >
                  删除
                </Button>
              </div>
            </div>
          </div>
        </div>
      </template>
      <Empty v-else description="暂无等级数据" />
    </Spin>

    <Button
      class="mm-tier-add-btn"
      type="dashed"
      block
      :disabled="!props.canManage"
      @click="emit('create')"
    >
      <template #icon>
        <IconifyIcon icon="lucide:plus" />
      </template>
      添加等级
    </Button>
  </div>
</template>
