import React, { createContext, ReactNode, useCallback, useContext } from 'react'
import { useAccount, useReadContract, useWriteContract } from 'wagmi'
import contractAbi from "../../../out/RaidGeld.sol/RaidGeld.json"
import { parseEther } from 'viem'

const contractAddress = "0xbd06B0878888bf4c6895704fa603a5ADf7e65c66"
const abi = contractAbi.abi

export interface PlayerContextType {
  isRegistered: boolean,
  user: null | string,
  balance: bigint,
  register: () => void;
}

const PlayerContext = createContext<PlayerContextType>({
  isRegistered: false,
  user: null,
  balance: BigInt(0),
  register: () => { },
});

const PlayerProvider = ({ children }: { children: ReactNode }) => {
  const { address, isConnected } = useAccount();
  const { writeContract } = useWriteContract();
  const { data: isRegistered } = useReadContract({
    address: contractAddress,
    abi,
    functionName: 'isRegistered',
    args: [address],
    query: {
      enabled: isConnected,
      refetchInterval: 5,
    }
  });

  console.log("IS REGISTERED", isRegistered, address)

  const { data: balance, error, refetch: refetchBalance } = useReadContract({
    address: contractAddress,
    abi,
    functionName: 'balanceOf',
    args: [address],
    query: {
      refetchInterval: 5,
      enabled: isConnected
    }
  });

  console.log(balance, error)

  const { data: playerData, refetch: refetchPlayerData } = useReadContract({
    address: contractAddress,
    abi,
    functionName: 'getPlayer',
    args: [address],
    query: {
      enabled: isConnected,
      refetchInterval: 15
    }
  });

  const register = useCallback(() => {
    console.log("START")
    const a = writeContract({
      abi,
      address: contractAddress,
      functionName: 'register',
      value: parseEther("0.0005"),
    })
    console.log(a)
  }, [writeContract])

  return (
    <PlayerContext.Provider value={{
      isRegistered: isRegistered as boolean,
      user: null,
      balance: balance as bigint,
      register
    }}>
      {children}
    </PlayerContext.Provider>
  );
}

export const usePlayer = () => {
  return useContext(PlayerContext);
}

export default PlayerProvider

