import { ref, reactive, computed, type ComputedRef } from 'vue';
import * as StakeContract from '@/contracts/stake';
import { waitForTransactionReceipt } from '@wagmi/core';
import type { Config } from '@wagmi/core';
import { config } from '@/wagmi';
import { useContractToast } from './useContractToast';
import { compactNumber, weiToNumber } from 'kraiken-lib/format';
import { decodeEventLog, type DecodeEventLogReturnType } from 'viem';
import { useWallet } from './useWallet';

const contractToast = useContractToast();
const wallet = useWallet();

enum StakeState {
  SignTransaction = 'SignTransaction',
  Waiting = 'Waiting',
  Unstakeable = 'Unstakeable',
}

interface PositionRemovedArgs {
  lastTaxTime: number;
  positionId: bigint;
  harbergPayout: bigint;
}

export function useUnstake() {
  const loading = ref();
  const waiting = ref();

  const state: ComputedRef<StakeState> = computed(() => {
    if (loading.value) {
      return StakeState.SignTransaction;
    } else if (waiting.value) {
      return StakeState.Waiting;
    } else {
      return StakeState.Unstakeable;
    }
  });

  async function exitPosition(positionId: bigint) {
    try {
      loading.value = true;
      const hash = await StakeContract.exitPosition(positionId);
      loading.value = false;
      waiting.value = true;
      const data = await waitForTransactionReceipt(config as Config, {
        hash: hash,
      });

      const topics = decodeEventLog({
        abi: StakeContract.StakeContract.abi,
        data: data.logs[2].data,
        topics: data.logs[2].topics,
      }) as DecodeEventLogReturnType & { args: PositionRemovedArgs };

      const eventArgs: PositionRemovedArgs = topics.args;

      const amount = compactNumber(weiToNumber(eventArgs.harbergPayout, wallet.balance.decimals));
      contractToast.showSuccessToast(amount, 'Success!', 'You unstaked', '', '$KRK');

      waiting.value = false;
      wallet.loadBalance();
    } catch (error) {
      contractToast.showFailToast((error as Error).name);
    } finally {
      loading.value = false;
      waiting.value = false;
    }
  }

  return reactive({ state, exitPosition });
}
