<script setup lang="ts">
import { onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { useTransferStore, OTHER_WALLET_TYPES } from '@/stores/transfer'
import type { OtherWalletType, WalletType } from '@/stores/transfer'
import { useToast } from '@/composables/useToast'
import { walletTypeLabel } from '@/utils/walletTypeLabel'

const { t } = useI18n()
const route = useRoute()
const store = useTransferStore()
const {
  wallets, from, to, amount, transferSymbol, loading, submitting, error,
  fromBalance, isSpotCoinTransfer, coinOptions,
} = storeToRefs(store)
const toast = useToast()

function wLabel(kind: WalletType | OtherWalletType) {
  return walletTypeLabel(t, kind)
}

/** store 内 `i18n:xxx` 前缀错误码转文案；接口原始文案原样展示 */
function trErr(msg: string | null) {
  if (!msg) {
    return ''
  }
  if (msg.startsWith('i18n:')) {
    return t(msg.slice(5))
  }
  return msg
}

async function onSubmit() {
  try {
    await store.submit()
    toast.success(t('transfer.success'))
  } catch {
    // 错误在表单内展示；toast 按需由接口返回信息处理
  }
}

watch(isSpotCoinTransfer, (v) => {
  if (v) {
    void store.loadSpotTransferAssets()
  }
}, { immediate: true })

watch(transferSymbol, () => {
  amount.value = ''
})

onMounted(async () => {
  try {
    await store.loadWallets()
    const q = route.query
    if (q.fromType || q.toType) {
      store.setFromTo((q.fromType as WalletType) || store.from, (q.toType as WalletType) || store.to)
    }
    if (isSpotCoinTransfer.value) {
      await store.loadSpotTransferAssets()
    }
  } catch (e) {
    toast.error(e instanceof Error ? e.message : t('common.loadFailed'))
  }
})
</script>

<template>
  <main class="page-main">
    <div class="page-container content">
      <div class="page-header">
        <RouterLink to="/assets" class="back-link">{{ t('deposit.backWithArrow') }}</RouterLink>
        <div class="title-row">
          <h1 class="page-title">{{ t('transfer.title') }}</h1>
          <RouterLink to="/assets/transfer/history" class="hist-link">{{ t('assets.transferRecord') }}</RouterLink>
        </div>
      </div>

      <div v-if="loading" class="loading-state"><div class="spinner" /></div>

      <div v-else class="form-card dark-card">
        <div v-if="isSpotCoinTransfer" class="form-group coin-row">
          <label class="form-label">{{ t('spot.transferModal.selectCoin') }}</label>
          <select v-model="transferSymbol" class="form-select">
            <option v-for="c in coinOptions" :key="c" :value="c">{{ c }}</option>
          </select>
        </div>
        <div class="from-to-row">
          <div class="side">
            <p class="side-lbl">{{ t('assets.transferFrom') }}</p>
            <div v-if="from === 'SPOT'" class="form-select form-select--readonly">{{ wLabel('SPOT') }}</div>
            <select v-else v-model="from" class="form-select">
              <option v-for="wt in OTHER_WALLET_TYPES" :key="wt" :value="wt">{{ wLabel(wt) }}</option>
            </select>
            <p class="side-bal">
              {{ t('assets.availableCoin', {
                available: fromBalance,
                coin: isSpotCoinTransfer ? transferSymbol : 'USDT',
              }) }}
            </p>
          </div>
          <button type="button" class="swap-btn" @click="store.swap()">⇄</button>
          <div class="side">
            <p class="side-lbl">{{ t('assets.transferTo') }}</p>
            <div
              v-if="from === 'SWAP' || from === 'FOLLOW' || from === 'SPOT_TRADING'"
              class="form-select form-select--readonly"
            >
              {{ wLabel('SPOT') }}
            </div>
            <select v-else v-model="to" class="form-select">
              <option v-for="wt in OTHER_WALLET_TYPES" :key="wt" :value="wt">{{ wLabel(wt) }}</option>
            </select>
            <p v-if="wallets.find(w => w.walletType === to)" class="side-bal">
              {{ t('transfer.balanceLabel') }}: {{ wallets.find(w => w.walletType === to)?.balance ?? '0' }} USDT
            </p>
          </div>
        </div>

        <div class="form-group">
          <div class="label-row">
            <label class="form-label">
              {{ isSpotCoinTransfer
                ? t('assets.amountCoin', { coin: transferSymbol })
                : t('assets.amountUsdt') }}
            </label>
            <button type="button" class="all-btn" @click="amount = fromBalance">{{ t('common.all') }}</button>
          </div>
          <input v-model="amount" type="number" class="form-input" placeholder="0.00" min="0">
        </div>

        <div class="tip-row">
          <span class="tip-icon">ℹ️</span>
          <span>{{ t('assets.freeTransfer') }}</span>
        </div>

        <p v-if="error" class="form-error">{{ trErr(error) }}</p>

        <button type="button" class="submit-btn" :disabled="submitting || !amount" @click="onSubmit">
          {{ submitting ? t('assets.transferring') : t('assets.confirmTransferBtn') }}
        </button>
      </div>
    </div>
  </main>
</template>

<style scoped>
.content { padding-top: var(--space-8); padding-bottom: var(--space-16); max-width: 520px; }
.page-header { margin-bottom: var(--space-8); }
.back-link { font-size: var(--text-small); color: var(--color-text-secondary); display: inline-block; margin-bottom: var(--space-3); text-decoration: none; }
.back-link:hover { color: var(--color-primary); }
.title-row { display: flex; align-items: center; justify-content: space-between; }
.page-title { font-size: var(--text-h1); font-weight: var(--fw-bold); color: var(--color-text-primary); }
.hist-link { font-size: var(--text-small); color: var(--color-primary); text-decoration: none; }
.loading-state { display: flex; justify-content: center; padding: var(--space-16); }
.spinner { width: 32px; height: 32px; border-radius: 50%; border: 2px solid var(--color-border); border-top-color: var(--color-primary); animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.form-card { padding: var(--space-6); }
.from-to-row { display: flex; align-items: flex-start; gap: var(--space-3); margin-bottom: var(--space-5); }
.side { flex: 1; }
.side-lbl { font-size: var(--text-caption); color: var(--color-text-secondary); margin-bottom: var(--space-2); }
.side-bal { font-size: var(--text-caption); color: var(--color-text-muted); margin-top: var(--space-2); }
.form-select { width: 100%; background: var(--color-bg-card); border: 1px solid var(--color-border); border-radius: var(--radius-md); padding: var(--space-3) var(--space-4); color: var(--color-text-primary); outline: none; box-sizing: border-box; }
.form-select--readonly { cursor: default; color: var(--color-text-secondary); }
.form-select option { background: #1a1a1a; }
.swap-btn { margin-top: 28px; background: var(--color-bg-card); border: 1px solid var(--color-border); border-radius: 50%; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; cursor: pointer; color: var(--color-text-secondary); font-size: 18px; flex-shrink: 0; }
.swap-btn:hover { border-color: var(--color-primary); color: var(--color-primary); }
.form-group { margin-bottom: var(--space-5); }
.form-label { font-size: var(--text-small); color: var(--color-text-secondary); }
.label-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--space-2); }
.all-btn { background: none; border: none; color: var(--color-primary); font-size: var(--text-small); cursor: pointer; }
.form-input { width: 100%; box-sizing: border-box; background: var(--color-bg-card); border: 1px solid var(--color-border); border-radius: var(--radius-md); padding: var(--space-3) var(--space-4); color: var(--color-text-primary); outline: none; }
.form-input:focus { border-color: var(--color-primary); }
.tip-row { font-size: var(--text-small); color: var(--color-text-muted); display: flex; align-items: center; gap: var(--space-2); margin-bottom: var(--space-5); }
.form-error { font-size: var(--text-small); color: var(--color-down); margin-bottom: var(--space-4); }
.submit-btn { width: 100%; padding: var(--space-4); background: var(--color-primary); border: none; border-radius: var(--radius-md); color: #000; font-size: var(--text-body); font-weight: var(--fw-semibold); cursor: pointer; }
.submit-btn:disabled { opacity: .5; cursor: not-allowed; }
</style>
