<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { useWithdrawStore } from '@/stores/withdraw'
import { useToast } from '@/composables/useToast'

const { t } = useI18n()
const store = useWithdrawStore()
const {
  availableBalance,
  transferableBalance,
  initLoading,
  initError,
  sendingCode,
  codeCountdown,
  submitting,
  formError,
  googleBound,
  networkList,
  selectedNetworkId,
  onchainSubCoins,
  onchainSubCoinsLoading,
  transferMainCoins,
  selectedTransferCoinIndex,
  onchainSelectedCoin,
  transferSelectedCoin,
  minTransferAmount,
} = storeToRefs(store)
const toast = useToast()

/** store 或通用 `i18n:键` 前缀转文案；其余原样（接口报错） */
function trErr(msg: string | null | undefined) {
  if (!msg) {
    return ''
  }
  if (msg.startsWith('i18n:')) {
    return t(msg.slice(5))
  }
  return msg
}

const activeTab = ref<'onchain' | 'transfer'>('onchain')

const toAddress = ref('')
const amount = ref('')
const fundPwd = ref('')
const emailCode = ref('')
const googleCode = ref('')
const onchainError = ref('')

const recipient = ref('')
const transferAmount = ref('')
const tfFundPwd = ref('')
const tfEmailCode = ref('')
const tfGoogleCode = ref('')
const transferError = ref('')

const onchainCoinSymbol = computed(() => store.getOnchainCoinSymbol())
const transferCoinSymbol = computed(() => store.getTransferCoinSymbol())
const fee = computed(() => store.getOnchainFee())
const minWithdraw = computed(() => store.getOnchainMinWithdraw())
const arrive = computed(() => {
  const a = Number(amount.value)
  const f = Number(fee.value)
  return (!a || a <= f) ? '0' : (a - f).toFixed(2)
})

function subCoinTabLabel(coin: { displayName: string; unit: string }) {
  return coin.displayName || coin.unit.toUpperCase()
}

function onSelectNetwork(networkId: number) {
  store.selectNetwork(networkId)
  amount.value = ''
}

function onSelectSubCoin(i: number) {
  store.selectSubCoin(i)
  amount.value = ''
}

function onTransferCoinChange() {
  transferAmount.value = ''
}

function onTabChange(tab: 'onchain' | 'transfer') {
  activeTab.value = tab
  amount.value = ''
  transferAmount.value = ''
}

onMounted(async () => {
  try {
    await store.init()
  } catch {
    toast.error(trErr(initError.value) || t('withdraw.initFailed'))
  }
})
onUnmounted(() => store.stopCountdown())

async function sendCode() {
  try {
    if (activeTab.value === 'onchain') {
      if (!toAddress.value.trim()) {
        onchainError.value = t('withdraw.errFillAddressBeforeCode')
        return
      }
      if (!amount.value) {
        onchainError.value = t('withdraw.errFillAmountBeforeCode')
        return
      }
      await store.sendEmailCode(store.getOnchainSubmitUnit(), toAddress.value.trim(), amount.value)
    } else {
      if (!recipient.value.trim()) {
        transferError.value = t('withdraw.errFillUidBeforeCode')
        return
      }
      if (!transferAmount.value) {
        transferError.value = t('withdraw.errFillTransferAmtBeforeCode')
        return
      }
      await store.sendEmailCode(store.getTransferSubmitUnit(), recipient.value.trim(), transferAmount.value)
    }
    toast.success(t('withdraw.codeSentToEmailToast'))
  } catch {
    toast.error(trErr(store.formError) || t('error.sendFailed'))
  }
}

async function submitOnchain() {
  onchainError.value = ''
  if (!toAddress.value.trim()) {
    onchainError.value = t('withdraw.errEnterWithdrawAddress')
    return
  }
  const a = Number(amount.value)
  if (!a || a <= 0) {
    onchainError.value = t('withdraw.errEnterWithdrawAmount')
    return
  }
  if (a < Number(minWithdraw.value)) {
    onchainError.value = t('withdraw.errMinWithdrawWithAmt', { min: minWithdraw.value, coin: onchainCoinSymbol.value })
    return
  }
  if (a > Number(availableBalance.value)) {
    onchainError.value = t('withdraw.errExceedWithdrawBalance')
    return
  }
  if (!fundPwd.value) {
    onchainError.value = t('withdraw.errEnterFundPassword')
    return
  }
  if (!emailCode.value) {
    onchainError.value = t('withdraw.errEnterEmailCode')
    return
  }
  if (!googleBound.value) {
    onchainError.value = t('withdraw.bindGoogleFirst')
    return
  }
  if (!googleCode.value.trim()) {
    onchainError.value = t('withdraw.errEnterGoogleCode')
    return
  }
  try {
    await store.submitOnchain({
      unit: store.getOnchainSubmitUnit(),
      amount: amount.value,
      address: toAddress.value.trim(),
      fee: fee.value,
      vcode: emailCode.value,
      jyPassword: fundPwd.value,
      vcode2: googleCode.value,
    })
    toast.success(t('withdraw.onchainSubmittedPendingToast'))
    toAddress.value = ''
    amount.value = ''
    fundPwd.value = ''
    emailCode.value = ''
    googleCode.value = ''
    store.stopCountdown()
  } catch {
    onchainError.value = trErr(store.formError) || t('withdraw.submitFailed')
  }
}

async function submitTransfer() {
  transferError.value = ''
  if (!recipient.value.trim()) {
    transferError.value = t('withdraw.errEnterRecipientUid')
    return
  }
  const a = Number(transferAmount.value)
  if (!a || a <= 0) {
    transferError.value = t('withdraw.errEnterTransferAmount')
    return
  }
  if (a < Number(minTransferAmount.value)) {
    transferError.value = t('withdraw.errMinTransferWithAmt', { min: minTransferAmount.value, coin: transferCoinSymbol.value })
    return
  }
  if (a > Number(transferableBalance.value)) {
    transferError.value = t('withdraw.errExceedTransferBalance')
    return
  }
  if (!tfFundPwd.value) {
    transferError.value = t('withdraw.errEnterFundPassword')
    return
  }
  if (!tfEmailCode.value) {
    transferError.value = t('withdraw.errEnterEmailCode')
    return
  }
  if (!googleBound.value) {
    transferError.value = t('withdraw.bindGoogleFirst')
    return
  }
  if (!tfGoogleCode.value.trim()) {
    transferError.value = t('withdraw.errEnterGoogleCode')
    return
  }
  try {
    await store.submitTransfer({
      unit: store.getTransferSubmitUnit(),
      amount: transferAmount.value,
      address: recipient.value.trim(),
      vcode: tfEmailCode.value,
      jyPassword: tfFundPwd.value,
      vcode2: tfGoogleCode.value,
    })
    toast.success(t('withdraw.transferSubmittedToast'))
    recipient.value = ''
    transferAmount.value = ''
    tfFundPwd.value = ''
    tfEmailCode.value = ''
    tfGoogleCode.value = ''
    store.stopCountdown()
  } catch {
    transferError.value = trErr(store.formError) || t('withdraw.submitFailed')
  }
}
</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('withdraw.title') }}</h1>
          <RouterLink to="/assets/withdraw/history" class="hist-link">{{ t('withdraw.recordTitle') }}</RouterLink>
        </div>
      </div>

      <div v-if="initLoading" class="loading-state"><div class="spinner" /></div>
      <div v-else-if="initError" class="error-state dark-card">
        <p>{{ trErr(initError) }}</p>
        <button class="retry-btn" @click="store.init()">{{ t('common.retry') }}</button>
      </div>

      <template v-else>
        <div class="mode-tabs">
          <button class="mode-tab" :class="{ active: activeTab === 'onchain' }" @click="onTabChange('onchain')">{{ t('withdraw.typeOnChainWithdraw') }}</button>
          <button class="mode-tab" :class="{ active: activeTab === 'transfer' }" @click="onTabChange('transfer')">{{ t('withdraw.typeInternalTransfer') }}</button>
        </div>

        <div class="form-card dark-card">
        <template v-if="activeTab === 'onchain'">
            <div class="form-group">
              <label class="form-label">{{ t('withdraw.withdrawNetworkLabel') }}</label>
              <div v-if="!networkList.length" class="empty-net">{{ t('deposit.noNetwork') }}</div>
              <div v-else class="network-tabs">
                <button
                  v-for="net in networkList"
                  :key="net.id"
                  type="button"
                  class="net-tab"
                  :class="{ active: selectedNetworkId === net.id }"
                  @click="onSelectNetwork(net.id)"
                >
                  {{ net.name }}{{ net.protocol ? ` · ${net.protocol}` : '' }}
                </button>
              </div>
            </div>

            <div v-if="selectedNetworkId" class="form-group">
              <label class="form-label">{{ t('withdraw.subCoin') }}</label>
              <div v-if="onchainSubCoinsLoading" class="sub-loading">
                <div class="spinner sm" />
              </div>
              <div v-else-if="!onchainSubCoins.length" class="empty-net">{{ t('deposit.noSubCoin') }}</div>
              <div v-else class="network-tabs">
                <button
                  v-for="(coin, i) in onchainSubCoins"
                  :key="coin.unit"
                  type="button"
                  class="net-tab"
                  :class="{ active: onchainSelectedCoin?.unit === coin.unit }"
                  @click="onSelectSubCoin(i)"
                >
                  {{ subCoinTabLabel(coin) }}
                </button>
              </div>
            </div>

            <p class="avail-tip">
              {{ t('withdraw.availWithdrawBalance') }}<strong>{{ availableBalance }} {{ onchainCoinSymbol }}</strong>
            </p>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.address') }}</label>
              <input
                v-model="toAddress"
                class="form-input"
                :placeholder="t('withdraw.addressForCoin', { coin: onchainCoinSymbol })"
              />
            </div>

            <div class="form-group">
              <div class="label-row">
                <label class="form-label">{{ t('withdraw.withdrawAmountCoin', { coin: onchainCoinSymbol }) }}</label>
                <button class="all-btn" @click="amount = availableBalance">{{ t('common.all') }}</button>
              </div>
              <input v-model="amount" type="number" class="form-input" placeholder="0.00" min="0" />
              <div class="fee-preview">
                <div class="fee-row"><span>{{ t('withdraw.fee') }}</span><span>{{ fee }} {{ onchainCoinSymbol }}</span></div>
                <div class="fee-row"><span>{{ t('withdraw.expectedArrival') }}</span><span class="arrive-val">{{ arrive || '—' }} {{ onchainCoinSymbol }}</span></div>
                <div class="fee-row">
                  <span>{{ t('withdraw.minWithdrawRowLabel') }}</span><span>{{ minWithdraw }} {{ onchainCoinSymbol }}</span>
                </div>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.fundPassword') }}</label>
              <input v-model="fundPwd" type="password" class="form-input" autocomplete="current-password" />
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.emailCode') }}</label>
              <div class="code-row">
                <input v-model="emailCode" type="text" maxlength="6" class="form-input" :placeholder="t('withdraw.codePlaceholder6Digits')" @input="emailCode = emailCode.replace(/\D/g, '')" />
                <button class="send-btn" :disabled="sendingCode || codeCountdown > 0" @click="sendCode">
                  {{ codeCountdown > 0 ? `${codeCountdown}s` : t('withdraw.sendVerificationCode') }}
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.googleCode') }}</label>
              <input v-model="googleCode" type="text" maxlength="6" class="form-input" :placeholder="t('withdraw.googlePlaceholder6')" inputmode="numeric" autocomplete="one-time-code" @input="googleCode = googleCode.replace(/\D/g, '')" />
            </div>

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

            <button class="submit-btn" :disabled="submitting || !onchainSelectedCoin" @click="submitOnchain">
              {{ submitting ? t('header.submitting') : t('withdraw.confirmWithdrawSubmit') }}
            </button>
        </template>

        <template v-else>
            <div v-if="transferMainCoins.length" class="form-group">
              <label class="form-label">{{ t('withdraw.mainCoinLabel') }}</label>
              <select
                v-model.number="selectedTransferCoinIndex"
                class="form-input coin-select"
                @change="onTransferCoinChange"
              >
                <option
                  v-for="(coin, i) in transferMainCoins"
                  :key="coin.unit"
                  :value="i"
                >
                  {{ subCoinTabLabel(coin) }}
                </option>
              </select>
              <p class="hint-line">{{ t('withdraw.transferMainCoinHint') }}</p>
            </div>

            <p class="avail-tip">
              {{ t('withdraw.availTransferBalance') }}<strong>{{ transferableBalance }} {{ transferCoinSymbol }}</strong>
            </p>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.recipientUidLabel') }}</label>
              <input v-model="recipient" class="form-input" :placeholder="t('withdraw.recipientUidPlaceholder')" />
            </div>

            <div class="form-group">
              <div class="label-row">
                <label class="form-label">{{ t('withdraw.transferAmountCoin', { coin: transferCoinSymbol }) }}</label>
                <button class="all-btn" @click="transferAmount = transferableBalance">{{ t('common.all') }}</button>
              </div>
              <input v-model="transferAmount" type="number" class="form-input" placeholder="0.00" min="0" />
              <div class="fee-preview">
                <div class="fee-row"><span>{{ t('withdraw.internalTransferFeeLabel') }}</span><span>{{ t('withdraw.free') }}</span></div>
                <div class="fee-row">
                  <span>{{ t('withdraw.minTransferRowLabel') }}</span><span>{{ minTransferAmount }} {{ transferCoinSymbol }}</span>
                </div>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.fundPassword') }}</label>
              <input v-model="tfFundPwd" type="password" class="form-input" autocomplete="current-password" />
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.emailCode') }}</label>
              <div class="code-row">
                <input v-model="tfEmailCode" type="text" maxlength="6" class="form-input" :placeholder="t('withdraw.codePlaceholder6Digits')" @input="tfEmailCode = tfEmailCode.replace(/\D/g, '')" />
                <button class="send-btn" :disabled="sendingCode || codeCountdown > 0" @click="sendCode">
                  {{ codeCountdown > 0 ? `${codeCountdown}s` : t('withdraw.sendVerificationCode') }}
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">{{ t('withdraw.googleCode') }}</label>
              <input v-model="tfGoogleCode" type="text" maxlength="6" class="form-input" :placeholder="t('withdraw.googlePlaceholder6')" inputmode="numeric" autocomplete="one-time-code" @input="tfGoogleCode = tfGoogleCode.replace(/\D/g, '')" />
            </div>

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

            <button class="submit-btn" :disabled="submitting || !transferSelectedCoin" @click="submitTransfer">
              {{ submitting ? t('header.submitting') : t('withdraw.confirmTransferSubmit') }}
            </button>
        </template>
        </div>
      </template>
    </div>
  </main>
</template>

<style scoped>
.content { padding-top: var(--space-8); padding-bottom: var(--space-16); max-width: 600px; }
.page-header { margin-bottom: var(--space-6); }
.back-link { font-size: var(--text-small); color: var(--color-text-secondary); display: inline-block; margin-bottom: var(--space-3); }
.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; }
.spinner.sm { width: 20px; height: 20px; }
.sub-loading { display: flex; padding: var(--space-2) 0; }
.empty-net { font-size: var(--text-small); color: var(--color-text-muted); padding: var(--space-2) 0; }
@keyframes spin { to { transform: rotate(360deg); } }
.error-state { padding: var(--space-8); text-align: center; color: var(--color-text-secondary); }
.retry-btn { margin-top: var(--space-4); background: transparent; border: 1px solid var(--color-primary); border-radius: var(--radius-md); color: var(--color-primary); padding: var(--space-2) var(--space-5); cursor: pointer; }
.mode-tabs { display: flex; border-bottom: 1px solid var(--color-border); margin-bottom: var(--space-5); }
.mode-tab { padding: var(--space-3) var(--space-6); background: none; border: none; border-bottom: 2px solid transparent; margin-bottom: -1px; color: var(--color-text-secondary); font-size: var(--text-body); cursor: pointer; transition: all var(--transition); }
.mode-tab.active { color: var(--color-primary); border-bottom-color: var(--color-primary); }
.form-card { padding: var(--space-6); }
.avail-tip { font-size: var(--text-small); color: var(--color-text-secondary); margin-bottom: var(--space-5); }
.avail-tip strong { color: var(--color-text-primary); }
.form-group { margin-bottom: var(--space-5); }
.form-label { display: block; font-size: var(--text-small); color: var(--color-text-secondary); margin-bottom: var(--space-2); }
.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); }
.form-input::placeholder { color: var(--color-text-muted); }
.coin-select {
  width: 100%;
  box-sizing: border-box;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='%23999' d='M1 1l5 5 5-5'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right var(--space-4) center;
  padding-right: calc(var(--space-4) + 20px);
  cursor: pointer;
}
.network-tabs { display: flex; gap: var(--space-2); flex-wrap: wrap; }
.net-tab { padding: var(--space-2) var(--space-4); border: 1px solid var(--color-border); border-radius: var(--radius-md); background: transparent; color: var(--color-text-secondary); font-size: var(--text-small); cursor: pointer; transition: all var(--transition); }
.net-tab:hover { border-color: var(--color-primary); color: var(--color-primary); }
.net-tab.active { border-color: var(--color-primary); background: rgba(240,185,11,.1); color: var(--color-primary); }
.network-hint { font-size: var(--text-small); color: var(--color-text-primary); padding: var(--space-2) 0; }
.hint-line { font-size: var(--text-caption); color: var(--color-text-muted); margin-top: var(--space-2); line-height: 1.5; }
.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; }
.fee-preview { background: var(--color-bg-card); border-radius: var(--radius-md); padding: var(--space-3) var(--space-4); margin-top: var(--space-3); display: flex; flex-direction: column; gap: var(--space-2); }
.fee-row { display: flex; justify-content: space-between; font-size: var(--text-small); color: var(--color-text-secondary); }
.arrive-val { color: var(--color-primary); font-weight: var(--fw-semibold); }
.code-row { display: flex; gap: var(--space-3); }
.code-row .form-input { flex: 1; }
.send-btn { white-space: nowrap; padding: 0 var(--space-4); background: transparent; border: 1px solid var(--color-primary); border-radius: var(--radius-md); color: var(--color-primary); font-size: var(--text-small); cursor: pointer; flex-shrink: 0; transition: background var(--transition); }
.send-btn:hover:not(:disabled) { background: rgba(240,185,11,.1); }
.send-btn:disabled { opacity: .5; cursor: not-allowed; }
.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>
