'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'

interface UserProfile {
  username: string
  first_name?: string
  avatarUrl?: string
}

export function Header() {
  const [user, setUser] = useState<UserProfile | null>(null)
  const router = useRouter()
  useEffect(() => {
    const token = localStorage.getItem('token')
    if (!token) {
      return
    }
    fetch('/api/auth/user/', {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(res => {
        if (!res.ok) throw new Error('unauth')
        return res.json()
      })
      .then(setUser)
      .catch(() => {
        localStorage.removeItem('token')
        router.push('/auth/login')
      })
  }, [router])

  const logout = () => {
    localStorage.removeItem('token')
    router.push('/')
  }

  return (
    <nav className="navbar navbar-expand bg-light fixed-top">
      <div className="container">
        <Link href="/" className="navbar-brand">
          <Image src="/assets/img/CAT.png" width={89} height={89} alt="CatLink"/>
        </Link>
        <div className="collapse navbar-collapse">
          {user ? (
            <div className="ms-auto d-flex align-items-center">
              <Link href="/dashboard" className="me-3 d-flex align-items-center">
                <Image
                  src={user.avatarUrl || '/assets/img/avatar-dhg.png'}
                  width={32}
                  height={32}
                  className="rounded-circle"
                  alt="avatar"
                />
                <span className="ms-2">{user.first_name || user.username}</span>
              </Link>
              <button className="btn btn-outline-danger" onClick={logout}>
                Выход
              </button>
            </div>
          ) : (
            <Link href="/auth/login" className="btn btn-primary ms-auto">
              Вход
            </Link>
          )}
        </div>
      </div>
    </nav>
  )
}
