import { useEffect, useReducer, useRef } from 'react';
import { BossLevel, usePlayer } from '../providers/PlayerProvider';
import styles from '../styles/Background.module.css';

const onCooldown = (lastRaidedAt: bigint) => (
  ((new Date()).getTime()
    - (parseInt(lastRaidedAt.toString()) * 1000 /* convert block time to seconds */))
  / 1000 /* convert milliseconds back to seconds*/
) <= 15

const emptyFn = () => { }

const bossLevelToClass: Record<BossLevel, string> = {
  0: styles.tower0,
  1: styles.tower1,
  2: styles.tower2,
  3: styles.tower3,
  4: styles.tower4,
  5: styles.tower5,
  6: styles.tower6,
}

const Tower = () => {
  const { raid, player, boss } = usePlayer();
  const isOnCooldown = useRef(false);
  const [, render] = useReducer(p => !p, false);
  const variant = boss?.variants[boss.level] ?? 0;

  useEffect(() => {
    const checkCooldownInterval = setInterval(() => {
      isOnCooldown.current = onCooldown(player?.last_raided_at ?? BigInt(0))
      render()
    }, 1000);
    return () => clearInterval(checkCooldownInterval)
  }, [player?.last_raided_at])

  return <div onClick={isOnCooldown.current ? emptyFn : raid} className={`
    ${styles.tower} 
    ${bossLevelToClass[variant]}
    ${styles.background_asset}
    ${isOnCooldown.current ? styles.cooldown : ""}
  `} />
}

export default Tower
