import React from 'react'
import { Link, useLocation } from 'react-router-dom'

import { getUser } from '../utils/storage'

export default function SideNav() {
  const location = useLocation()
  const isActive = (path) => location.pathname === path
  const [reqCount, setReqCount] = React.useState(0)
  const user = getUser()

  React.useEffect(() => {
    if (!user?.id) return
    const fetchCount = async () => {
      try {
        const res = await fetch(`http://localhost/landingpage1/lomba/friends.php?user_id=${user.id}&type=requests`)
        const data = await res.json()
        if (Array.isArray(data)) setReqCount(data.length)
      } catch { }
    }
    fetchCount()
    // Poll every 10 seconds to keep it updated
    const interval = setInterval(fetchCount, 10000)
    return () => clearInterval(interval)
  }, [user?.id])

  const base = 'ui w-full text-left px-4 py-2 rounded-lg font-semibold border-2 flex justify-between items-center'
  const active = 'bg-onme-blue text-onme-whiteSoft border-onme-blue'
  const normal = 'bg-white text-gray-800 border-onme-softBlue hover:border-onme-blue'

  return (
    <nav className="p-4 flex flex-col gap-2">
      <Link to="/" className={`${base} ${isActive('/') ? active : normal}`}>Beranda</Link>
      <Link to="/profile" className={`${base} ${isActive('/profile') ? active : normal}`}>Profile</Link>
      <Link to="/friends" className={`${base} ${isActive('/friends') ? active : normal}`}>
        <span>Friends</span>
        {reqCount > 0 && (
          <span className="bg-red-500 text-white text-xs font-bold px-2 py-0.5 rounded-full shadow-sm animate-pulse">
            {reqCount}
          </span>
        )}
      </Link>
      <Link to="/settings" className={`${base} ${isActive('/settings') ? active : normal}`}>Settings</Link>
    </nav>
  )
}
