<template>
  <div class="search-payee gradient-background-circles">
    <!-- 使用 GeneralHeader 替换 MobileHeader -->
    <GeneralHeader
      :showLanguageList="true"
      :title="t('search_payee')"
      :backQuery="backQuery"
      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/Aslan/search.png"
            alt=""
            style="width: 1.5em; 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"
          style="
            border: none;
            color: rgba(0, 0, 0, 0.4);
            font-weight: 600;
            background-color: transparent;
          "
          @click="performSearch"
        >
          {{ t('search') }}
        </button>
        <button
          v-else
          style="border: none; font-weight: 600; background-color: transparent"
          @click="clearSearch"
        >
          {{ t('cancel') }}
        </button>
      </div>

      <!-- 角色检查加载状态 -->
      <div v-if="isLoadingRole" class="loading-state">
        <LoadingContent spinner-margin="0 auto 16px">{{ t('checking_permissions') }}...</LoadingContent>
      </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; gap: 4px">
            <!-- 基本信息 -->
            <div style="flex: 1; min-width: 0; display: flex; align-items: center; gap: 4px">
              <!-- 头像 -->
              <div
                style="
                  width: 3.5em;
                  align-self: stretch;

                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <img
                  :src="user.avatar || ''"
                  style="
                    display: block;
                    width: 100%;
                    aspect-ratio: 1/1;
                    border-radius: 50%;
                    object-fit: cover;
                  "
                  @error="handleAvatarImageError"
                />
              </div>

              <!-- 账号信息 -->
              <div
                style="
                  flex: 1;
                  min-width: 0;
                  align-self: stretch;

                  display: flex;
                  flex-direction: column;
                  gap: 4px;
                "
              >
                <div
                  style="
                    font-weight: 700;

                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                >
                  {{ user.name }}
                </div>
                <div style="font-size: 0.9em; font-weight: 500; color: rgba(0, 0, 0, 0.4)">
                  {{ t('user_id_prefix') }} {{ user.account || user.id }}
                </div>
              </div>
            </div>

            <!-- 添加按钮 -->
            <button
              style="
                width: auto;

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

                font-size: 0.9em;
                font-weight: 500;
                padding: 2px 8px;
                cursor: pointer;
              "
              @click="selectUser(user)"
            >
              {{ t('add') }}
            </button>
          </div>

          <!-- 身份徽章 -->
          <div style="margin-top: 4px; margin-left: 3em; height: 20px">
            <img
              src="../../../assets/icon/identity/coinSeller.png"
              alt=""
              height="100%"
              style="display: block; object-fit: cover"
            />
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isSearching" class="loading-state">
        <LoadingContent spinner-margin="0 auto 16px">{{ t('searching') }}...</LoadingContent>
      </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, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { setSelectedPayee } from '@/utils/payeeStore.js'
import { showError } from '@/utils/toast.js'
import { setDocumentDirection } from '@/locales/i18n'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'

import { userBankSearchUserProfile } from '@/api/wallet.js'

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

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()
const backQuery = ref(route.query || null)

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

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

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

// 执行搜索
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(), 'TRANSFER')

    if (response.status && response.body) {
      // 根据新的API返回数据结构进行映射
      const user = {
        id: response.body.id,
        account: response.body.account,
        name: response.body.userNickname,
        avatar: response.body.userAvatar,
        sex: response.body.userSex,
        age: response.body.age,
        countryName: response.body.countryName,
        countryCode: response.body.countryCode,
        accountStatus: response.body.accountStatus,
      }
      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
  maskLayerShow.value = true
}

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

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

  // 检查是否来自 availableIncome 页面
  if (Object.keys(route.query).length > 0) {
    console.log('route.query:', route.query)

    try {
      // 先执行路由替换
      await router.replace({
        path: route.query.from,
        query: {
          activeAction: route.query.activeAction,
        },
      })
      console.log('路由替换成功')
    } catch (error) {
      console.error('路由替换失败:', error)
      // 如果替换失败，仍然执行返回操作
      router.go(-1)
    }
  } else {
    // 如果没有 from 参数，直接返回上一页并关闭弹窗
    router.go(-1)
    maskLayerShow.value = false
  }
}

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

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

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

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

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

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

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

@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;
  }
}
</style>
