/**
 * SessionManager Component - Session management and timeout
 */

import { useEffect, useState } from 'react'
import { useAccount } from 'wagmi'
import { useNavigate } from 'react-router-dom'
import { startSession, getSessionTimeRemaining, isSessionValid, endSession } from '../../utils/sessionManager'
import { useAdmin } from '../../contexts/AdminContext'

export default function SessionManager() {
  const { address } = useAccount()
  const navigate = useNavigate()
  const { setImpersonationAddress } = useAdmin()
  const [timeRemaining, setTimeRemaining] = useState(0)

  useEffect(() => {
    if (address) {
      startSession(address)
    }
  }, [address])

  useEffect(() => {
    const interval = setInterval(() => {
      if (!isSessionValid()) {
        endSession()
        setImpersonationAddress(null)
        navigate('/')
        alert('Session expired. Please reconnect your wallet.')
        return
      }
      setTimeRemaining(getSessionTimeRemaining())
    }, 1000)

    return () => clearInterval(interval)
  }, [navigate, setImpersonationAddress])

  const formatTime = (ms: number): string => {
    const minutes = Math.floor(ms / 60000)
    const seconds = Math.floor((ms % 60000) / 1000)
    return `${minutes}:${seconds.toString().padStart(2, '0')}`
  }

  if (timeRemaining === 0) return null

  return (
    <div className="fixed bottom-4 right-4 bg-black/80 backdrop-blur-xl rounded-lg p-3 border border-white/20 shadow-lg">
      <div className="flex items-center gap-2">
        <div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" />
        <span className="text-white text-sm">
          Session: {formatTime(timeRemaining)} remaining
        </span>
      </div>
    </div>
  )
}
