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

    <div class="content">
      <!-- 搜索框 -->
      <div style="display: flex; gap: 4px">
        <div
          style="
            flex: 1;
            background-color: white;
            border-radius: 32px;
            border: 1px solid #fff;
            box-sizing: border-box;

            display: flex;
            align-items: center;
            gap: 4px;
            padding: 4px 12px;
          "
        >
          <img src="../assets/icon/search.png" alt="" width="16px" style="opacity: 0.6" />
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="t('search_user')"
            class="search-input"
            style="
              flex: 1;
              border: none;
              padding: 4px 0;
              background: transparent;
              outline: none;
              width: 100%;
            "
            @keyup.enter="performSearch"
          />
        </div>

        <button
          v-if="!hasSearched && searchQuery"
          class="search-btn"
          style="
            border: none;
            color: rgba(0, 0, 0, 0.4);
            font-weight: 600;
            background-color: transparent;
          "
          @click="performSearch"
        >
          {{ t('search') }}
        </button>
        <button
          v-else
          class="search-btn"
          style="border: none; font-weight: 600; background-color: transparent"
          @click="clearSearch"
        >
          {{ t('cancel') }}
        </button>
      </div>

      <!-- 角色检查加载状态 -->
      <div v-if="isLoadingRole" class="loading-state">
        <div class="loading-spinner"></div>
        <p>{{ t('checking_permissions') }}...</p>
      </div>

      <!-- 搜索结果 -->
      <div v-else-if="searchResults.length > 0" style="margin: 20px 0">
        <div
          v-for="user in searchResults"
          :key="user.id"
          style="
            padding: 16px;
            border-radius: 12px;
            margin-bottom: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            background-color: white;
          "
        >
          <div style="display: flex; align-items: center; justify-content: space-between">
            <div style="flex: 1; display: flex; align-items: center; gap: 4px">
              <div
                style="
                  width: 50px;
                  height: 50px;
                  border-radius: 25px;
                  background-color: #8b5cf6;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  color: white;
                  font-weight: 600;
                  overflow: hidden;
                "
              >
                <img
                  v-if="user.avatar"
                  :src="user.avatar"
                  style="width: 100%; height: 100%; object-fit: cover; display: block"
                />
                <span v-else>{{ user.name.charAt(0) }}</span>
              </div>
              <div class="user-details">
                <h4>{{ user.name }}</h4>
                <div style="display: flex; align-items: center">
                  <p>ID</p>
                  <p>:</p>
                  <p>{{ user.account || user.id }}</p>
                </div>
              </div>
            </div>
            <button class="add-btn" @click="selectUser(user)">{{ t('add') }}</button>
          </div>
          <div style="display: flex; gap: 2px; margin-top: 8px; margin-left: 50px; height: 20px">
            <img
              v-if="user.isHost"
              src="../assets/icon/host.png"
              alt=""
              height="100%"
              style="object-fit: cover"
            />
            <img
              v-if="user.isAgency"
              src="../assets/icon/agency.png"
              alt=""
              height="100%"
              style="object-fit: cover"
            />
            <img
              v-if="user.hasSalary"
              src="../assets/icon/RA.png"
              alt=""
              height="100%"
              style="object-fit: cover"
            />
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isSearching" class="loading-state">
        <div class="loading-spinner"></div>
        <p>{{ t('searching') }}...</p>
      </div>
    </div>

    <!-- 弹窗遮罩层 -->
    <maskLayer :maskLayerShow="maskLayerShow" @click="maskLayerShow = false">
      <div
        style="
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
        @click.stop
      >
        <div
          style="
            width: 80%;
            border-radius: 12px;
            background: #fff;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
          "
        >
          <div style="color: rgba(0, 0, 0, 0.8); font-weight: 800">{{ t('tips') }}</div>
          <div style="color: rgba(0, 0, 0, 0.5); font-weight: 600; text-align: center">
            {{ t('confirm_transfer_to_user') }}
          </div>
          <div
            style="width: 100%; display: flex; justify-content: space-around; align-items: center"
          >
            <div
              style="
                padding: 12px 20px;
                border-radius: 12px;
                border: 1px solid #e6e6e6;
                color: rgba(0, 0, 0, 0.4);
                font-weight: 800;
              "
              @click="Cancel"
            >
              {{ t('cancel') }}
            </div>
            <div
              style="
                padding: 12px 20px;
                border-radius: 12px;
                background: linear-gradient(
                  152deg,
                  rgba(198, 112, 255, 0.6) 7.01%,
                  rgba(119, 38, 255, 0.6) 92.99%
                );
                color: rgba(255, 255, 255, 0.8);
                font-weight: 800;
              "
              @click="Confirm"
            >
              {{ t('confirm') }}
            </div>
          </div>
        </div>
      </div>
    </maskLayer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import GeneralHeader from '@/components/GeneralHeader.vue'
import { userBankCheckTransfer, userBankSearchUserProfile } from '../api/wallet.js'
import { setSelectedPayee } from '../utils/payeeStore.js'
import { showError } from '@/utils/toast.js'
import maskLayer from '@/components/MaskLayer.vue'
import { setDocumentDirection } from '@/locales/i18n'

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()

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

const fromLottery = computed(() => route.query?.from == 'lottery')
const pageTitle = computed(() =>
  route.query?.from == 'lottery' ? t('add_recharge_agent') : t('search_payee')
)

const searchQuery = ref('')
const searchResults = ref([])
const isSearching = ref(false)
const hasSearched = ref(false)
const userRole = ref('')
const isLoadingRole = ref(false)
const selectedUserType = ref('')
const showTypeSelector = ref(false)

const maskLayerShow = ref(false)
const selectedUser = ref({})

// 模拟用户数据 - 根据角色显示不同的用户
const allUsers = {
  TEAM_OWN: [
    {
      id: '1234567890',
      name: 'Agent User',
      type: 'AGENT',
      isHost: false,
      isAgency: true,
      hasSalary: false,
    },
    {
      id: '0987654321',
      name: 'BD Manager',
      type: 'BD',
      isHost: false,
      isAgency: true,
      hasSalary: true,
    },
    {
      id: '1122334455',
      name: 'Host Anchor',
      type: 'ANCHOR',
      isHost: true,
      isAgency: false,
      hasSalary: true,
    },
  ],
  TEAM_MEMBER: [
    {
      id: '1234567890',
      name: 'Team Agent',
      type: 'AGENT',
      isHost: false,
      isAgency: true,
      hasSalary: false,
    },
    {
      id: '0987654321',
      name: 'BD Manager',
      type: 'BD',
      isHost: false,
      isAgency: true,
      hasSalary: true,
    },
  ],
  BD: [
    {
      id: '1234567890',
      name: 'Agent User',
      type: 'AGENT',
      isHost: false,
      isAgency: true,
      hasSalary: false,
    },
  ],
  default: [
    {
      id: '1234567890',
      name: 'Default User',
      type: 'USER',
      isHost: false,
      isAgency: false,
      hasSalary: false,
    },
  ],
}

// 根据角色获取可搜索的用户列表
const availableUsers = computed(() => {
  return allUsers[userRole.value] || allUsers['default']
})

// 根据用户角色获取可选择的用户类型
// const availableUserTypes = computed(() => {
//   switch (userRole.value) {
//     case 'TEAM_OWN':
//       return [
//         { label: 'Agent', value: 'AGENT' },
//         { label: 'BD Manager', value: 'BD' },
//         { label: 'Anchor', value: 'ANCHOR' },
//       ]
//     case 'TEAM_MEMBER':
//       return [
//         { label: 'Agent', value: 'AGENT' },
//         { label: 'BD Manager', value: 'BD' },
//       ]
//     case 'BD':
//       return [{ label: 'Agent', value: 'AGENT' }]
//     default:
//       return [{ label: 'User', value: 'USER' }]
//   }
// })

// 检查用户转账角色
const checkUserRole = async () => {
  isLoadingRole.value = true

  try {
    const response = await userBankCheckTransfer()

    if (response.status && response.body) {
      // 根据接口返回的role设置用户角色
      userRole.value = response.body.role || ''

      // 设置默认的用户类型
      if (userRole.value === 'TEAM_OWN') {
        selectedUserType.value = 'ANCHOR' // TEAM_OWN 默认选择 ANCHOR
      } else {
        selectedUserType.value = 'AGENT' // 其他角色默认选择 AGENT
      }
    } else {
      userRole.value = ''
      selectedUserType.value = 'USER'
    }
  } catch (error) {
    console.error('Failed to check user role:', error)
    userRole.value = ''
    selectedUserType.value = 'USER'
  } finally {
    isLoadingRole.value = false
  }
}

// 执行搜索
const performSearch = async () => {
  console.log('searchQuery.value:', searchQuery.value)

  if (!searchQuery.value.trim()) {
    searchResults.value = []
    return
  }

  isSearching.value = true
  hasSearched.value = false

  try {
    const response = await userBankSearchUserProfile(searchQuery.value.trim())

    if (response.status && response.body) {
      // 根据新的API返回数据结构进行映射
      const user = {
        id: response.body.id,
        account: response.body.account,
        name: response.body.userNickname,
        avatar: response.body.userAvatar,
        type: selectedUserType.value,
        sex: response.body.userSex,
        age: response.body.age,
        countryName: response.body.countryName,
        countryCode: response.body.countryCode,
        accountStatus: response.body.accountStatus,
        // 根据类型设置标签
        isHost: selectedUserType.value === 'ANCHOR',
        isAgency: ['AGENT', 'BD'].includes(selectedUserType.value),
        hasSalary: ['ANCHOR', 'BD'].includes(selectedUserType.value),
      }
      searchResults.value = [user]
    } else {
      searchResults.value = []
    }
  } catch (error) {
    console.error('Search failed:', error)
    searchResults.value = []
    showError(t('user_not_found_or_search_failed'))
  } finally {
    isSearching.value = false
    hasSearched.value = true
  }
}

// 清除搜索
const clearSearch = () => {
  hasSearched.value = false
  searchQuery.value = ''
  searchResults.value = []
}

// 选择用户
const selectUser = (user) => {
  selectedUser.value = user
  if (fromLottery.value) {
    maskLayerShow.value = true
  } else {
    Confirm()
  }
}

const Cancel = () => {
  selectedUser.value = {}
  maskLayerShow.value = false
}

const Confirm = () => {
  // 将选中的用户信息保存到全局状态
  setSelectedPayee({ ...selectedUser.value })

  // 返回到 Transfer 页面
  // router.push('/transfer')
  router.go(-1)
}

// 获取角色描述
const getRoleDescription = (role) => {
  switch (role) {
    case 'TEAM_OWN':
      return 'Agents, BD Managers, Anchors'
    case 'TEAM_MEMBER':
      return 'Agents, BD Managers'
    case 'BD':
      return 'Agents'
    default:
      return 'Users'
  }
}

watch(
  () => searchQuery.value,
  () => {
    if (hasSearched.value) {
      hasSearched.value = false
    }
  }
)

// 页面加载时检查用户角色
onMounted(() => {
  checkUserRole()
})
</script>

<style scoped>
* {
  color: rgba(0, 0, 0, 0.8);
  font-family: 'SF Pro Text';
}

.search-payee {
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

.content {
  padding: 16px;
  position: relative;
  z-index: 2;
}

/* 用户类型选择器 */
.user-type-selector {
  margin-bottom: 12px;
}

.user-type-selector label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.type-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.type-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 16px;
  background-color: white;
  color: #666;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.type-btn.active {
  background-color: #8b5cf6;
  color: white;
  border-color: #8b5cf6;
}

.type-btn:active {
  transform: scale(0.98);
}

.search-input {
  font-size: 16px;
}

.search-input::placeholder {
  color: #999;
}

.search-btn {
  font-size: 16px;
}

.user-details h4 {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 4px;
}

.user-details p {
  font-size: 14px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.4);
}

.add-btn {
  background-color: transparent;
  color: rgba(0, 0, 0, 0.4);
  border: 1px solid #e6e6e6;
  border-radius: 12px;

  font-size: 14px;
  font-weight: 500;
  padding: 2px 8px;
  cursor: pointer;
}

/* 空状态和提示 */
.empty-state,
.search-hint {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

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

.empty-state p,
.search-hint p {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
}

.empty-state span,
.search-hint span {
  font-size: 14px;
  color: #666;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 40px 20px;
}

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

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

.loading-state p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .search-input {
    font-size: 14px;
  }

  .search-btn {
    font-size: 13px;
  }

  .type-btn {
    padding: 5px 10px;
    font-size: 11px;
  }

  .user-details h4 {
    font-size: 15px;
  }

  .user-details p {
    font-size: 13px;
  }

  .add-btn {
    font-size: 13px;
  }
}

/* RTL支持 */
[dir='rtl'] .user-details {
  text-align: right;
}

[dir='rtl'] .add-btn {
  margin-left: 0;
  margin-right: 12px;
}
</style>
