import { ref, reactive, computed } from 'vue';
import { type ComputedRef } from 'vue';
import { config } from '@/wagmi';
// import axios from "axios";
import { waitForTransactionReceipt, watchAccount, type Config } from '@wagmi/core';
import { type WatchAccountReturnType } from '@wagmi/core';
import * as HarbContract from '@/contracts/harb';
// import HarbJson from "@/assets/contracts/harb.json";
import { useWallet } from './useWallet';
// import { compactNumber, formatBigIntDivision } from "@/utils/helper";

const wallet = useWallet();

const loading = ref(false);
const waiting = ref(false);
const ubiDue = HarbContract.ubiDue;
let unwatch: WatchAccountReturnType;

enum ClaimState {
  NothingToClaim = 'NothingToClaim',
  StakeAble = 'StakeAble',
  SignTransaction = 'SignTransaction',
  Waiting = 'Waiting',
  NotEnoughApproval = 'NotEnoughApproval',
}

export function useClaim() {
  const state: ComputedRef<ClaimState> = computed(() => {
    if (loading.value) {
      return ClaimState.SignTransaction;
    } else if (ubiDue.value === 0n) {
      return ClaimState.NothingToClaim;
    } else if (waiting.value) {
      return ClaimState.Waiting;
    } else {
      return ClaimState.StakeAble;
    }
  });

  async function claimUbi() {
    try {
      const address = wallet.account.address!;

      loading.value = true;
      const hash = await HarbContract.claimUbi(address);
      loading.value = false;
      waiting.value = true;
      await waitForTransactionReceipt(config as Config, {
        hash: hash,
      });
    } catch (_error) {
    } finally {
      loading.value = false;
      waiting.value = false;
    }
  }

  if (!unwatch) {
    unwatch = watchAccount(config as Config, {
      async onChange(data) {
        if (data.address) {
          await HarbContract.setHarbContract();
        }
      },
    });
  }
  return reactive({ claimUbi, ubiDue, state });
}
