<template>
  <div class="message gradient-background-circles">
    <!-- 使用 GeneralHeader 替换 MobileHeader -->
    <GeneralHeader
      :showLanguageList="true"
      :title="t('users_message')"
      color="black"
      style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
    />

    <div style="padding: 16px; position: relative; z-index: 2">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>{{ t('loading') }}...</p>
      </div>

      <div v-else style="display: flex; flex-direction: column; gap: 12px">
        <div
          v-for="message in messages"
          :key="message.id"
          style="
            background-color: white;
            padding: 12px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <div class="user-info" style="width: calc(100% - 110px)">
            <div
              class="user-avatar"
              style="
                width: 35px;
                border-radius: 20px;
                background-color: rgba(0, 0, 0, 0.1);
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-weight: 600;
                overflow: hidden;
              "
            >
              <img
                v-if="message.avatar"
                :src="message.avatar || ''"
                :alt="message.name"
                style="display: block; width: 100%; aspect-ratio: 1/1; object-fit: cover"
                @error="handleAvatarImageError"
              />
              <div v-else>{{ message.name?.charAt(0) || 'U' }}</div>
            </div>
            <div style="width: 70%">
              <h4
                style="
                  margin-bottom: 4px;
                  font-weight: 700;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                {{ message.name || t('unknown_user') }}
              </h4>
              <div>
                <div style="display: flex; align-items: center">
                  <p style="font-size: 0.8em; font-weight: 500; color: rgba(0, 0, 0, 0.4)">ID</p>
                  <p
                    style="
                      font-size: 0.8em;
                      font-weight: 500;
                      color: rgba(0, 0, 0, 0.4);
                      margin: 0 2px;
                    "
                  >
                    :
                  </p>
                  <p style="font-size: 0.8em; font-weight: 500; color: rgba(0, 0, 0, 0.4)">
                    {{ message.account || message.userId }}
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="action-buttons" style="display: flex; gap: 4px">
            <button class="agree-btn" @click="handleAgree(message)">{{ t('agree') }}</button>
            <button class="refuse-btn" @click="handleRefuse(message)">{{ t('refuse') }}</button>
          </div>
        </div>
      </div>

      <div v-if="!loading && messages.length === 0" class="empty-state">
        <div class="empty-icon">📨</div>
        <p>{{ t('no_messages') }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getTeamId } from '@/utils/userStore.js'
import { showError, showSuccess, showWarning } from '@/utils/toast.js'
import { setDocumentDirection } from '@/locales/i18n'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'

import { getApplyRecord } from '@/api/teamBill.js'
import { processUserApply } from '@/api/wallet.js'

import GeneralHeader from '@/components/GeneralHeader.vue'

const { t, locale } = useI18n()

// 监听语言变化并设置文档方向
locale.value && setDocumentDirection(locale.value)

const loading = ref(false)
const messages = ref([])

// 模拟消息数据
const mockMessages = [
  {
    id: '1234567890',
    name: 'User1',
    avatar: '',
    type: 'team_join_request',
  },
]

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const response = await getApplyRecord(getTeamId(), 'WAIT')

    if (response.status && response.body) {
      // 根据新的接口结构映射数据
      messages.value = response.body.map((item) => ({
        id: item.id,
        reason: item.reason,
        teamId: item.teamId,
        status: item.status,
        createTime: item.createTime,
        // 用户信息映射
        userId: item.createUserProfile.id,
        account: item.createUserProfile.account,
        name: item.createUserProfile.userNickname,
        avatar: item.createUserProfile.userAvatar,
        userSex: item.createUserProfile.userSex,
        age: item.createUserProfile.age,
        countryName: item.createUserProfile.countryName,
        countryCode: item.createUserProfile.countryCode,
      }))
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  } finally {
    loading.value = false
  }
}

// 同意申请
const handleAgree = async (message) => {
  try {
    const response = await processUserApply({
      id: message.id,
      status: 'AGREE',
    })

    if (response.status) {
      showSuccess(
        t('approved_application', {
          name: message.name,
        }),
      )
      // 从列表中移除
      const index = messages.value.findIndex((m) => m.id === message.id)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
    } else {
      showError(t('operation_failed'))
    }
  } catch (error) {
    console.error('同意申请失败:', error)
    showError(t('operation_failed'))
  }
}

// 拒绝申请
const handleRefuse = async (message) => {
  try {
    const response = await processUserApply({
      id: message.id,
      status: 'REJECT',
    })

    if (response.status) {
      showWarning(
        t('rejected_application', {
          name: message.name,
        }),
      )
      // 从列表中移除
      const index = messages.value.findIndex((m) => m.id === message.id)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
    } else {
      showError(t('operation_failed'))
    }
  } catch (error) {
    console.error('拒绝申请失败:', error)
    showError(t('operation_failed'))
  }
}

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

<style scoped>
* {
  color: rgba(0, 0, 0, 0.8);
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #8b5cf6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 4px;
}

.agree-btn,
.refuse-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 20px;
  font-weight: 600;
}

.agree-btn {
  background: linear-gradient(
    152deg,
    rgba(198, 112, 255, 0.6) 7.01%,
    rgba(119, 38, 255, 0.6) 92.99%
  );
  color: white;
}

.refuse-btn {
  background-color: transparent;
  border: 1px solid #bb92ff;
  color: #bb92ff;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}

@media screen and (max-width: 360px) {
  * {
    font-size: 10px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 12px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }
}

/* RTL支持 */
[dir='rtl'] .user-avatar {
  margin-right: 0;
  margin-left: 4px;
}

[dir='rtl'] .user-info {
  text-align: right;
}

[dir='rtl'] .action-buttons {
  flex-direction: row-reverse;
}
</style>
