<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 Ether
      </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>ETH</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 {FixedNumber} from "ethers";
import {WithdrawNativeTransaction} from "@/blockchain/transaction.js";

const s = useStore()
const props = defineProps(['modelValue', 'vault', 'balance'])
const emit = defineEmits(['update:modelValue'])
const balanceFloat = computed(() => Number(props.balance)/1e18)
const floatAmount = ref(0)

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

</script>

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

</style>
