<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { 
  listPendingInvites, 
  acceptInvite, 
  rejectInvite,
  type AppUser 
} from '@/api/app/appUser'
import { useRouter } from 'vue-router'
import { TeamOutlined, PlusOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const invites = ref<AppUser[]>([])
const loading = ref(false)

// 待确认邀请数量
const pendingCount = computed(() => invites.value.length)

// 是否有待确认邀请
const hasPending = computed(() => pendingCount.value > 0)

// 加载邀请列表
async function loadInvites() {
  try {
    loading.value = true
    invites.value = await listPendingInvites()
  } catch (error) {
    console.error('加载邀请列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 接受邀请
async function handleAccept(invite: AppUser) {
  if (!invite.id) return
  try {
    await acceptInvite(invite.id)
    message.success('已接受邀请，加入应用成功')
    // 移除已处理的邀请
    invites.value = invites.value.filter(i => i.id !== invite.id)
    // 刷新页面或跳转到应用
    setTimeout(() => {
      router.push('/developer/apps')
    }, 500)
  } catch (error: any) {
    message.error(error.message || '接受邀请失败')
  }
}

// 拒绝邀请
async function handleReject(invite: AppUser) {
  if (!invite.id) return
  Modal.confirm({
    title: '确认拒绝邀请？',
    content: `拒绝后将无法加入应用「${invite.productName || '未知应用'}」`,
    okText: '确认拒绝',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await rejectInvite(invite.id!)
        message.success('已拒绝邀请')
        invites.value = invites.value.filter(i => i.id !== invite.id)
      } catch (error: any) {
        message.error(error.message || '拒绝邀请失败')
      }
    }
  })
}

// 查看全部邀请
function viewAllInvites() {
  router.push('/console/invites')
}

onMounted(() => {
  loadInvites()
})
</script>

<template>
  <ClientOnly>
    <a-dropdown v-if="hasPending" :trigger="['hover']" placement="bottomRight">
      <a-badge :count="pendingCount" :offset="[-2, 2]">
        <a-button type="text" class="invite-bell-btn">
          <template #icon>
            <TeamOutlined style="font-size: 18px; color: #fff" />
          </template>
        </a-button>
      </a-badge>
      <template #overlay>
        <a-menu class="invite-dropdown-menu">
          <a-menu-item-group title="应用邀请">
            <a-menu-item v-for="invite in invites.slice(0, 3)" :key="invite.id" class="invite-menu-item">
              <div class="invite-item-content">
                <a-avatar 
                  :src="invite.icon || '/logo.png'" 
                  :size="32"
                  class="app-icon"
                />
                <div class="invite-info">
                  <div class="app-name">{{ invite.productName || '未知应用' }}</div>
                  <div class="invite-meta">
                    <span class="role-tag" :class="invite.role">
                      {{ invite.role === 'owner' ? '所有者' : 
                         invite.role === 'admin' ? '管理员' : 
                         invite.role === 'developer' ? '开发者' : '访客' }}
                    </span>
                  </div>
                </div>
                <div class="invite-actions">
                  <a-button 
                    type="primary" 
                    size="small"
                    shape="circle"
                    class="action-btn accept"
                    @click.stop="handleAccept(invite)"
                  >
                    <CheckOutlined />
                  </a-button>
                  <a-button 
                    size="small"
                    shape="circle"
                    class="action-btn reject"
                    @click.stop="handleReject(invite)"
                  >
                    <CloseOutlined />
                  </a-button>
                </div>
              </div>
            </a-menu-item>
          </a-menu-item-group>
          <a-menu-divider v-if="invites.length > 0" />
          <a-menu-item key="view-all" @click="viewAllInvites">
            <span style="text-align: center; display: block;">
              查看全部 {{ pendingCount }} 个邀请
            </span>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </ClientOnly>
</template>

<style scoped>
.invite-bell-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invite-bell-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}
</style>

<style>
/* 下拉菜单样式 */
.invite-dropdown-menu {
  min-width: 280px !important;
  max-width: 320px;
}

.invite-dropdown-menu .ant-dropdown-menu-item-group-title {
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.invite-menu-item {
  padding: 12px 16px !important;
  height: auto !important;
  line-height: normal !important;
}

.invite-menu-item:hover {
  background-color: #f5f5f5 !important;
}

.invite-item-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.invite-info {
  flex: 1;
  min-width: 0;
}

.app-name {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.invite-meta {
  margin-top: 2px;
}

.role-tag {
  font-size: 11px;
  padding: 1px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.role-tag.owner {
  background: #fff2e8;
  color: #fa541c;
}

.role-tag.admin {
  background: #e6f7ff;
  color: #1890ff;
}

.role-tag.developer {
  background: #f6ffed;
  color: #52c41a;
}

.role-tag.viewer {
  background: #f9f0ff;
  color: #722ed1;
}

.invite-actions {
  display: flex;
  gap: 6px;
}

.action-btn {
  width: 24px;
  height: 24px;
  min-width: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.accept {
  background: #52c41a;
  border-color: #52c41a;
}

.action-btn.accept:hover {
  background: #73d13d;
  border-color: #73d13d;
}

.action-btn.reject {
  background: #ff4d4f;
  border-color: #ff4d4f;
  color: #fff;
}

.action-btn.reject:hover {
  background: #ff7875;
  border-color: #ff7875;
}

.app-icon {
  flex-shrink: 0;
}
</style>
