import { useI18n } from 'vue-i18n'
import { resolveSpotOrderStatusKey, type SpotOrderStatusKey } from '@/utils/spotI18n'

export type { SpotOrderStatusKey }
export { resolveSpotOrderStatusKey }

export function useSpotI18n() {
  const { t } = useI18n()

  const sideLabel = (side: 'buy' | 'sell' | string) =>
    String(side).toLowerCase() === 'sell' ? t('spot.side.sell') : t('spot.side.buy')

  const orderTypeLabel = (type: 'limit' | 'market' | string, typeCode?: number) => {
    const isMarket = type === 'market' || typeCode === 2
    return isMarket ? t('spot.orderType.market') : t('spot.orderType.limit')
  }

  const orderStatusLabel = (key: SpotOrderStatusKey | string) =>
    t(`spot.orderStatus.${key}` as 'spot.orderStatus.pending')

  const orderStatusFromOrder = (o: {
    statusKey?: SpotOrderStatusKey
    statusCode: number
    tradedAmount: number
    amount: number
    status?: string
  }) => {
    const key = o.statusKey ?? resolveSpotOrderStatusKey(o.statusCode, o.status)
    if (key === 'cancelled' && o.tradedAmount > 0 && o.tradedAmount < o.amount) {
      return orderStatusLabel('partial')
    }
    return orderStatusLabel(key)
  }

  const RECORD_TYPE_I18N_KEY: Record<number, string> = {
    1: 'transferIn',
    2: 'transferOut',
    3: 'orderFreeze',
    4: 'cancelUnfreeze',
    5: 'trade',
    6: 'fee',
    7: 'unfreeze',
  }

  /** account_record.type：1–7，与后端 AccountRecordType 一致 */
  const recordTypeLabel = (type: number) => {
    const name = RECORD_TYPE_I18N_KEY[type]
    if (name) {
      return t(`spot.recordType.${name}` as 'spot.recordType.transferIn')
    }
    return t('spot.recordType.unknown', { type })
  }

  return {
    sideLabel,
    orderTypeLabel,
    orderStatusLabel,
    orderStatusFromOrder,
    recordTypeLabel,
    marketPrice: () => t('spot.orderType.market'),
  }
}
