<script setup lang="ts">
type OrderType = "limit" | "market";
type TradeAction = "buy" | "sell";

interface TradeFormData {
  orderType: OrderType;
  price: string;
  amount: string;
  total: string;
}

const props = defineProps<{
  action: TradeAction;
}>();

const formData = reactive<TradeFormData>({
  orderType: "limit",
  price: "",
  amount: "",
  total: "",
});

// TODO: 后续从API获取用户余额
// const { data: balance } = await client.api.wallet.balances.get({ query: { accountType: 'trading' } })
const availableBalance = ref({
  base: "0.00000000", // BTC
  quote: "10000.00", // USDT
});

const isBuy = computed(() => props.action === "buy");
const buttonColor = computed(() => isBuy.value ? "success" : "danger");
const buttonText = computed(() => isBuy.value ? "买入 BTC" : "卖出 BTC");

// 计算总价
watch(() => [formData.price, formData.amount], () => {
  if (formData.price && formData.amount) {
    const price = Number.parseFloat(formData.price);
    const amount = Number.parseFloat(formData.amount);
    if (!Number.isNaN(price) && !Number.isNaN(amount)) {
      formData.total = (price * amount).toFixed(2);
    }
  }
});

// 根据总价计算数量
watch(() => formData.total, (newTotal) => {
  if (newTotal && formData.price) {
    const total = Number.parseFloat(newTotal);
    const price = Number.parseFloat(formData.price);
    if (!Number.isNaN(total) && !Number.isNaN(price) && price > 0) {
      formData.amount = (total / price).toFixed(8);
    }
  }
});

function setPercentage(percent: number) {
  if (isBuy.value) {
    // 买入：根据USDT余额计算
    const balance = Number.parseFloat(availableBalance.value.quote);
    const total = balance * percent;
    formData.total = total.toFixed(2);
  }
  else {
    // 卖出：根据BTC余额计算
    const balance = Number.parseFloat(availableBalance.value.base);
    formData.amount = (balance * percent).toFixed(8);
  }
}

async function handleSubmit() {
  // TODO: 后续调用交易API
  // await client.api.trading.order.post({
  //   symbol: 'BTC_USDT',
  //   side: props.action,
  //   type: formData.orderType,
  //   price: formData.orderType === 'limit' ? formData.price : undefined,
  //   quantity: formData.amount
  // })
  console.log("提交订单", {
    action: props.action,
    ...formData,
  });
}
</script>

<template>
  <div class="trade-form">
    <!-- 订单类型切换 -->
    <div class="order-type-tabs">
      <button
        :class="{ active: formData.orderType === 'limit' }"
        @click="formData.orderType = 'limit'"
      >
        限价
      </button>
      <button
        :class="{ active: formData.orderType === 'market' }"
        @click="formData.orderType = 'market'"
      >
        市价
      </button>
    </div>

    <!-- 可用余额 -->
    <div class="balance-info">
      <span class="label">可用</span>
      <span class="value">
        {{ isBuy ? availableBalance.quote : availableBalance.base }}
        {{ isBuy ? 'USDT' : 'BTC' }}
      </span>
    </div>

    <!-- 价格输入 -->
    <div v-if="formData.orderType === 'limit'" class="input-group">
      <label>价格</label>
      <div class="input-wrapper">
        <input
          v-model="formData.price"
          type="number"
          placeholder="请输入价格"
        >
        <span class="unit">USDT</span>
      </div>
    </div>

    <!-- 数量输入 -->
    <div class="input-group">
      <label>数量</label>
      <div class="input-wrapper">
        <input
          v-model="formData.amount"
          type="number"
          placeholder="请输入数量"
        >
        <span class="unit">BTC</span>
      </div>
    </div>

    <!-- 百分比选择 -->
    <div class="percentage-buttons">
      <button @click="setPercentage(0.25)">
        25%
      </button>
      <button @click="setPercentage(0.5)">
        50%
      </button>
      <button @click="setPercentage(0.75)">
        75%
      </button>
      <button @click="setPercentage(1)">
        100%
      </button>
    </div>

    <!-- 总额 -->
    <div class="input-group">
      <label>总额</label>
      <div class="input-wrapper">
        <input
          v-model="formData.total"
          type="number"
          placeholder="请输入总额"
        >
        <span class="unit">USDT</span>
      </div>
    </div>

    <!-- 提交按钮 -->
    <ion-button
      expand="block"
      :color="buttonColor"
      class="submit-button"
      @click="handleSubmit"
    >
      {{ buttonText }}
    </ion-button>
  </div>
</template>

<style scoped>
.trade-form {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-type-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.order-type-tabs button {
  flex: 1;
  padding: 8px 0;
  background: transparent;
  border: none;
  color: var(--ion-text-color-step-400);
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.order-type-tabs button.active {
  color: var(--ion-color-primary);
  border-bottom-color: var(--ion-color-primary);
}

.balance-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--ion-text-color-step-400);
  margin-bottom: 4px;
}

.balance-info .value {
  color: var(--ion-text-color);
  font-weight: 500;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.input-group label {
  font-size: 12px;
  color: var(--ion-text-color-step-400);
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  background: var(--ion-color-light);
  border-radius: 8px;
  padding: 12px;
}

.input-wrapper input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  font-size: 14px;
  color: var(--ion-text-color);
}

.input-wrapper input::placeholder {
  color: var(--ion-text-color-step-600);
}

.input-wrapper .unit {
  font-size: 12px;
  color: var(--ion-text-color-step-400);
  margin-left: 8px;
}

.percentage-buttons {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.percentage-buttons button {
  padding: 6px 0;
  background: var(--ion-color-light);
  border: none;
  border-radius: 6px;
  font-size: 12px;
  color: var(--ion-text-color);
  cursor: pointer;
  transition: all 0.2s;
}

.percentage-buttons button:active {
  transform: scale(0.95);
  background: var(--ion-color-light-shade);
}

.submit-button {
  margin-top: 8px;
  --border-radius: 8px;
  font-weight: 600;
}
</style>
