<template>
  <v-text-field type="number" inputmode="numeric" pattern="[0-9]*\.?[0-9]*" v-model="amount" variant="outlined"
                density="compact"
                :hint="available" :persistent-hint="true"
                min="0"
                class="amount py-2" :color="color"
                :label="props.order.amountIsTokenA ?
                (multiplier ? 'Amount each' : 'Amount') :
                ((multiplier ? 'Value each in ' : 'Value in ')+co.selectedSymbol.quote.s)">
    <template #prepend>
      <v-btn v-if="!multiplier"
             variant="outlined" :color="color" class="ml-3"
             :text="(props.order.buy ? 'Buy ' : 'Sell ') + co.selectedSymbol.base.s"
             @click="props.order.buy=!props.order.buy"/>
    </template>
    <template #prepend-inner>
      <v-btn variant="text" text="max" class="px-0" size="small"
             :disabled="!maxAmount || props.order.amountIsTokenA===props.order.buy && !co.price" @click="setMax"/>
    </template>
    <template #append-inner>
      <v-btn :text="props.order.amountIsTokenA?co.baseToken.s:co.quoteToken.s+' worth'"
             :color="color" variant="text" @click="toggleAmountToken" style="width: 7em"/>
    </template>
  </v-text-field>
</template>

<script setup>
import {useChartOrderStore} from "@/orderbuild.js";
import {computed, ref} from "vue";
import {useStore} from "@/store/store.js";

const props = defineProps(['order', 'multiplier', 'color'])

const s = useStore()
const co = useChartOrderStore()

const amount = computed({
  get() {
    let result = props.order.amount
    if (result !== null && props.multiplier)
      result /= props.multiplier
    return result
  },
  set(v) {
    if (v !== null && props.multiplier)
      v *= props.multiplier
    props.order.amount = v
  }
})

const available = computed(()=>{
  const max = maxAmount.value
  return max === null ? '' : `Available: ${maxAmount.value} ${inToken.value.s}`
})

const inToken = computed( ()=>props.order.buy ? co.quoteToken : co.baseToken )

const maxAmount = computed(()=>{
  const token = inToken.value;
  if (!token)
    return null
  const balance = s.balances[token.a]
  if( !balance )
    return null
  return balance / 10**token.d
})

const lastMaxValue = ref(-1)

function setMax() {
  let amount = maxAmount.value
  if (amount) {
    const order = props.order
    const price = co.price
    if (order.amountIsTokenA===order.buy) {
      if (order.buy)
        amount /= price
      else
        amount *= price
    }
    amount = Number(amount.toPrecision(7))
    lastMaxValue.value = amount
    order.amount = amount
  }
}

function toggleAmountToken() {
  const order = props.order
  order.amountIsTokenA=!order.amountIsTokenA
  if (order.amount === lastMaxValue.value)
    setMax()
}

</script>

<style scoped lang="scss">
.amount {
  max-width: 30em;
}
</style>