<template>
  <div
    class="lucid-glass-bar flex h-full w-full flex-col justify-between rounded-4xl! border-1 border-white py-[32px] pb-[22px]"
  >
    <div>
      <div class="mb-3 flex min-h-[88px] flex-col items-center">
        <Transition name="fade" mode="out-in">
          <UserCenterSkeleton v-if="isUserLoading" type="header" layout="desktop" />
          <div v-else>
            <div class="flex items-center">
              <img src="./avatar.png" class="size-[60px]" alt="" />
              <div class="ml-2 flex flex-col justify-center text-white">
                <div class="text-base font-semibold">{{ userInfo.email }}</div>
                <div class="flex items-center text-base font-semibold">
                  <span class="mr-0.5 text-3xl">🌞</span> {{ referralText }}
                </div>
              </div>
            </div>
            <div class="mt-7 mb-1 ml-[18px] flex justify-between font-semibold text-[#ADFF5B]">
              专属代理链接

              <Button
                variant="link"
                class="mr-6 h-auto p-0 text-sm font-bold text-[#999] underline outline-none hover:text-[#666]"
                @click="withdrawalLogDialogRef?.show()"
              >
                提现记录
              </Button>
            </div>
            <div
              class="mb-[10px] flex h-[50px] w-full items-center justify-between rounded-[32px] bg-[#ADFF5B] px-4 font-medium text-black"
            >
              {{ userInfo.share_link }}
              <CopyIcon class="size-5 cursor-pointer" @click="copy(userInfo.share_link)" />
            </div>
            <div
              class="flex min-h-[90px] w-full items-center justify-between rounded-[25px] bg-[#ADFF5B] px-4 font-medium text-black"
            >
              <div>
                <div class="flex items-center text-xl font-semibold">佣金账户余额</div>
                <div class="text-3xl font-black">
                  $ {{ (userInfo.commission / 100 || 0).toFixed(2) }}
                </div>
              </div>
              <Button
                variant="ghost"
                class="hover:bg-transparent"
                :disabled="isCheckingWithdrawal"
                @click="handleWithdrawClick"
              >
                {{ hasPendingWithdrawal ? '审核中' : '点击提现' }}
              </Button>
            </div>
          </div>
        </Transition>
      </div>
    </div>
    <WalletDialog ref="walletDialogRef" :commission="userInfo.commission || 0" @confirm="init" />
    <WithdrawalLogDialog ref="withdrawalLogDialogRef" />
    <div>
      <div class="flex flex-col gap-[10px] px-6 pt-8 pb-4">
        <div
          class="flex h-[50px] w-full items-center justify-between rounded-[32px] bg-[#222222] px-4 pr-6 leading-[50px] font-medium"
        >
          我的邀请码：{{ userInfo.refer_code }}
          <CopyIcon class="size-5 cursor-pointer text-white" @click="copy(userInfo.refer_code)" />
        </div>
        <div class="mt-[-2px] mb-1 px-2 text-[11px] leading-snug text-[#ADFF5B]">
          *
          提醒：如果客户没有海外苹果ID，使用官方提供的ID会导致绑定失败，用户可以手动输入此邀请码绑定代理。
        </div>
        <div class="h-[50px] w-full rounded-[32px] bg-[#222222] px-4 leading-[50px] font-medium">
          历史佣金总计：$ {{ (inviteStats.friendly_count / 100).toFixed(2) }}
        </div>
        <div class="h-[50px] w-full rounded-[32px] bg-[#222222] px-4 leading-[50px] font-medium">
          历史推荐人数：{{ inviteStats.history_count }}人
        </div>
        <Button
          variant="outline"
          @click="logout"
          class="h-[50px] w-full rounded-[32px] border-2 border-white bg-transparent text-xl font-bold text-white transition-all hover:bg-white/90 active:scale-[0.98]"
        >
          退出登录
        </Button>
      </div>

      <div class="text-center text-xs text-white tabular-nums">注册时间：{{ formattedDate }}</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import UserCenterSkeleton from '@/components/user-center/UserCenterSkeleton.vue'
import { Button } from '@/components/ui/button'
import WalletDialog from './components/WalletDialog.vue'
import WithdrawalLogDialog from './components/WithdrawalLogDialog.vue'
import CopyIcon from './copy.svg?component'
import { computed, onMounted, ref } from 'vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

const router = useRouter()
const walletDialogRef = ref<InstanceType<typeof WalletDialog> | null>(null)
const withdrawalLogDialogRef = ref<InstanceType<typeof WithdrawalLogDialog> | null>(null)
const userInfo = ref({
  email: '',
  created_at: '',
  share_link: '',
  commission: 0,
  referral_percentage: 0,
})
const inviteStats = ref({
  friendly_count: 0,
  history_count: 0,
})
const isUserLoading = ref(true)
const isCheckingWithdrawal = ref(false)
const hasPendingWithdrawal = ref(false)
async function init() {
  // 1. 用户信息 & 设备列表
  isUserLoading.value = true
  request
    .get('/api/v1/public/user/info')
    .then((res: any) => {
      userInfo.value = res
      const emailInfo = res.auth_methods?.find((item: any) => item.auth_type === 'email')
      if (emailInfo) {
        userInfo.value.email = emailInfo.auth_identifier
        localStorage.setItem('UserEmail', emailInfo.auth_identifier)
      }
    })
    .finally(() => {
      isUserLoading.value = false
    })

  // 2. 邀请统计
  request.get('/api/v1/public/user/invite/stats').then((res: any) => {
    inviteStats.value = res
  })

  checkPendingWithdrawal()
}

onMounted(() => {
  init()
})

const formattedDate = computed(() => {
  const dateStr = userInfo?.value.created_at
  if (!dateStr) return '加载中...'

  const date = new Date(dateStr)

  // 使用 Intl 格式化，输出类似：2026/01/29 17:00
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).format(date)
})

const referralText = computed(() => {
  const percentage = Number(userInfo.value.referral_percentage || 0)
  if (percentage <= 0) return '暂未激活比例，请联系客服激活'
  if (percentage <= 20) return `初级合伙人 返佣比例${percentage}%`
  if (percentage <= 39) return `高级合伙人 返佣比例${percentage}%`
  return `超级合伙人 返佣比例${percentage}%`
})

async function handleWithdrawClick() {
  if (hasPendingWithdrawal.value) {
    toast.info('已有提现申请审核中，请勿重复提交')
    return
  }
  if (isCheckingWithdrawal.value) return

  const canWithdraw = await checkPendingWithdrawal(true)
  if (canWithdraw) {
    walletDialogRef.value?.show()
  }
}

async function checkPendingWithdrawal(showErrorToast = false) {
  try {
    isCheckingWithdrawal.value = true
    const res: any = await request.get('/api/v1/public/user/withdrawal_log', {
      page: 1,
      size: 20,
    })
    hasPendingWithdrawal.value = (res?.list || []).some((item: any) => item.status === 0)
    if (hasPendingWithdrawal.value) {
      toast.info('已有提现申请审核中，请勿重复提交')
      return false
    }
    return true
  } catch (error) {
    console.error('Check withdrawal logs error:', error)
    if (showErrorToast) {
      toast.error('提现记录检查失败，请稍后重试')
    }
    return false
  } finally {
    isCheckingWithdrawal.value = false
  }
}

function copy(text: string) {
  navigator.clipboard.writeText(text).then(() => {
    toast.success('已复制到剪贴板')
  })
}

function logout() {
  router.push('/')
  localStorage.removeItem('Authorization')
}
</script>
