import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import styles from "../styles/Header.module.css"
import { usePlayer } from "../providers/PlayerProvider";
import { useAccount } from 'wagmi';
import dynamic from "next/dynamic";
import { formatUnits } from "viem";

const Header = () => {
  const { isConnected } = useAccount();
  const { isRegistered, register, balance } = usePlayer();
  const [count, setCount] = useState("0")
  const [perSecond, setPerSecond] = useState("0")

  useEffect(() => {
    if (balance != null) {
      setCount(formatUnits(balance, 4))
    }
  }, [balance])

  const title = useMemo(() => {
    return isRegistered ? `SLAY THE MOLOCH` :
      !isConnected ? "Connect your wallet traveler ☝️  and then ..." :
        "Click here to start 😈"
  }, [isConnected, isRegistered])

  const subtitle = useMemo(() => {
    if (isRegistered) {
      return <p className={styles.counter}>{count} GELD</p>
    } else {
      return <p className={styles.counter}>SLAY THE MOLOCH</p>
    }
  }, [isRegistered, count])

  const perSecondParagraph = useMemo(() => {
    return (isRegistered) ?
      <p className={styles.counter_per_seconds}>per second: {perSecond}</p>
      : null
  }, [isRegistered, perSecond])

  const onRegister = useCallback(() => {
    if (isRegistered) return
    register();
  }, [isRegistered, register])

  return <header onClick={onRegister} className={styles.header}>
    {count.current} {balance}
    <h1 className={styles.title}>{title}</h1>
    {subtitle}
    {perSecondParagraph}
  </header>
}

// export default Header

export default dynamic(() => Promise.resolve(Header), {
  ssr: false,
});
