import React, { createContext, ReactNode, useCallback, useContext, useEffect } 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;
  raid: () => void
}

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

const PlayerProvider = ({ children }: { children: ReactNode }) => {
  const { address, isConnected } = useAccount();
  const { writeContract, error } = useWriteContract();


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

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

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

  console.log(playerData)

  useEffect(() => {
    console.warn(error, playerData)
  }, [error])

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

  const raid = useCallback(() => {
    writeContract({
      abi,
      address: contractAddress,
      functionName: 'raid',
    })
  }, [writeContract])

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

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

export default PlayerProvider

