<template>
  <v-dialog :model-value="modelValue" @update:modelValue="$emit('update:modelValue', $event)">
    <v-card>
      <v-card-title>
        <v-icon icon="mdi-down-arrow"/>&nbsp;Withdraw {{ token.symbol }}
      </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>{{ token.symbol }}</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 {contractOrNull} from "@/blockchain/contract.js"
import {vaultAbi} from "@/blockchain/abi.js";
import {pendTransaction} from "@/blockchain/wallet.js";
import {FixedNumber} from "ethers";

const s = useStore()
const props = defineProps(['modelValue', 'vault', 'token'])
const emit = defineEmits(['update:modelValue'])
const balance = computed(() => {
  console.log('balance', props.vault, props.token, s.vaultBalances)
  return s.vaultBalances[props.vault][props.token.address] || 0
})
const balanceFloat = computed(() => tokenFloat(props.token, balance.value))
const floatAmount = ref(0)

function withdraw() {
  const vaultAddr = props.vault
  const valueStr = floatAmount.value.toString();
  const amount = FixedNumber.fromString(valueStr,{decimals:props.token.decimals, width:256, signed: false}).value;
  console.log('pending withdrawl', valueStr, amount, props.token.symbol)
  if( amount === 0n )
    return
  pendTransaction(async (signer)=>{
    const vault = contractOrNull(vaultAddr, vaultAbi, signer)
    return await vault['withdraw(address,uint256)'](props.token.address, amount)
  })
  emit('update:modelValue', false)
}

</script>

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

</style>
