<template>
  <v-dialog :model-value="modelValue" @update:modelValue="$emit('update:modelValue', $event)">
    <v-card style="max-width: 25em" class="mx-auto">
      <v-card-title>
        <v-icon icon="mdi-arrow-down-bold" color="grey-darken-1"/>&nbsp;Withdraw {{ token.s }}
      </v-card-title>
      <v-card-item>
        <v-text-field class="text-end" type="number" variant="outlined" :min="0" :max="balanceFloat"
                      v-model="floatAmount" :step="balanceFloat/10">
          <template v-slot:prepend-inner>
            <v-btn variant="text" text="max" @click="floatAmount=balanceFloat"/>
          </template>
          <template v-slot:append-inner>
            <span style="max-width: 6em">{{ token.s }}</span>
          </template>
        </v-text-field>
        <v-card-actions>
          <v-btn text="Cancel" @click="$emit('update:modelValue', false)"/>
          <v-btn text="Withdraw" color="red" @click="withdraw"/>
        </v-card-actions>
      </v-card-item>
    </v-card>
  </v-dialog>
</template>

<script setup>
import {useStore} from "@/store/store";
import {computed, ref} from "vue";
import {tokenFloat} from "@/misc.js";
import {vaultContract} from "@/blockchain/contract.js"
import {pendTransaction} from "@/blockchain/wallet.js";
import {FixedNumber} from "ethers";
import {WithdrawTransaction} from "@/blockchain/transaction.js";

const s = useStore()
const props = defineProps(['modelValue', 'vault', 'token'])
const emit = defineEmits(['update:modelValue'])
const balance = computed(() => {
  const b = s.getBalance(props.token?.a)
  console.log('balance', b)
  // const b = s.vaultBalances[props.vault][props.token.address];
  return b === undefined ? 0n : BigInt(b)
})
const balanceFloat = computed(() => {
  let balance = tokenFloat(props.token, s.getBalance(props.token?.a))
  balance /= 10**props.token.d
  console.log('balanceFloat', balance, s.getBalance(props.token?.a), props.token)
  return balance
})
const floatAmount = ref(0)

function withdraw() {
  const vaultAddr = props.vault
  const valueStr = floatAmount.value.toString();
  const amount = floatAmount.value === balanceFloat.value ? balance.value :
      FixedNumber.fromString(valueStr,{decimals:props.token.d, width:256, signed: false}).value;
  if( amount === 0n )
    return
  console.log('pending withdrawal', valueStr, amount, props.token.s)
  new WithdrawTransaction(s.chainId, vaultAddr, props.token, amount).submit()
  floatAmount.value = 0
  emit('update:modelValue', false)
}

</script>

<style scoped lang="scss">
@use "src/styles/vars" as *;

</style>
