import { useState, useEffect } from 'react'
import { Link, NavLink } from 'react-router'
import { PencilSquareIcon, UserCircleIcon } from '@heroicons/react/24/solid'
import { SunIcon, MoonIcon, ComputerDesktopIcon, HomeIcon, ClockIcon, UsersIcon, RssIcon, SparklesIcon, Cog6ToothIcon, QuestionMarkCircleIcon } from '@heroicons/react/24/outline'
import { useAuth } from '~/lib/auth-context'
import { getStoredTheme, persistTheme, applyTheme, type Theme } from '~/lib/theme'
import Avatar from '~/components/Avatar'

export default function Nav() {
  const { session, loading } = useAuth()
  const [theme, setThemeState] = useState<Theme>('system')
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null)

  useEffect(() => {
    if (!session) { setAvatarUrl(null); return }
    let cancelled = false
    fetch(`https://api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(session.sub)}`)
      .then((r) => r.ok ? r.json() : null)
      .then((data: { avatar?: string } | null) => {
        if (!cancelled) setAvatarUrl(data?.avatar ?? null)
      })
      .catch(() => {})
    return () => { cancelled = true }
  }, [session?.sub])

  useEffect(() => {
    setThemeState(getStoredTheme())
    // Keep in sync when OS preference changes while in system mode
    const mq = window.matchMedia('(prefers-color-scheme: dark)')
    const handler = () => { if (getStoredTheme() === 'system') applyTheme('system') }
    mq.addEventListener('change', handler)
    return () => mq.removeEventListener('change', handler)
  }, [])

  function cycleTheme() {
    const next: Theme = theme === 'system' ? 'dark' : theme === 'dark' ? 'light' : 'system'
    persistTheme(next)
    setThemeState(next)
  }

  const themeLabel = theme === 'dark' ? 'Dark mode' : theme === 'light' ? 'Light mode' : 'System theme'

  return (
    <nav className="sticky top-0 z-50 border-b border-stone-200 dark:border-stone-800 bg-stone-50/90 dark:bg-stone-950/90 backdrop-blur-sm">
      <div className="px-4 md:px-8 h-14 flex items-center gap-5">
        <Link
          to="/"
          className="flex items-center gap-1.5 text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200 transition-colors"
          aria-label="Home"
        >
          <HomeIcon className="size-5 shrink-0" />
          <span className="hidden md:inline text-sm">Home</span>
        </Link>

        <NavLink
          to="/recent"
          aria-label="Recent"
          className={({ isActive }) =>
            `flex items-center gap-1.5 transition-colors ${
              isActive
                ? 'text-stone-900 dark:text-stone-100'
                : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
            }`
          }
        >
          <ClockIcon className="size-5 shrink-0" />
          <span className="hidden md:inline text-sm">Recent</span>
        </NavLink>

        {!loading && session && (
          <NavLink
            to="/following"
            aria-label="Following"
            className={({ isActive }) =>
              `flex items-center gap-1.5 transition-colors ${
                isActive
                  ? 'text-stone-900 dark:text-stone-100'
                  : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
              }`
            }
          >
            <UsersIcon className="size-5 shrink-0" />
            <span className="hidden md:inline text-sm">Following</span>
          </NavLink>
        )}

        {!loading && session && (
          <NavLink
            to="/subscriptions"
            aria-label="Subscriptions"
            className={({ isActive }) =>
              `flex items-center gap-1.5 transition-colors ${
                isActive
                  ? 'text-stone-900 dark:text-stone-100'
                  : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
              }`
            }
          >
            <RssIcon className="size-5 shrink-0" />
            <span className="hidden md:inline text-sm">Subscriptions</span>
          </NavLink>
        )}

        {!loading && session && (
          <NavLink
            to="/suggestions"
            aria-label="Suggestions"
            className={({ isActive }) =>
              `flex items-center gap-1.5 transition-colors ${
                isActive
                  ? 'text-stone-900 dark:text-stone-100'
                  : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
              }`
            }
          >
            <SparklesIcon className="size-5 shrink-0" />
            <span className="hidden md:inline text-sm">Suggestions</span>
          </NavLink>
        )}

        {!loading && session && (
          <NavLink
            to="/settings"
            aria-label="Settings"
            className={({ isActive }) =>
              `flex items-center gap-1.5 transition-colors ${
                isActive
                  ? 'text-stone-900 dark:text-stone-100'
                  : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
              }`
            }
          >
            <Cog6ToothIcon className="size-5 shrink-0" />
            <span className="hidden md:inline text-sm">Settings</span>
          </NavLink>
        )}

        <NavLink
          to="/help"
          aria-label="Help"
          className={({ isActive }) =>
            `flex items-center gap-1.5 transition-colors ${
              isActive
                ? 'text-stone-900 dark:text-stone-100'
                : 'text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200'
            }`
          }
        >
          <QuestionMarkCircleIcon className="size-5 shrink-0" />
          <span className="hidden md:inline text-sm">Help</span>
        </NavLink>

        <div className="flex-1" />

        <button
          onClick={cycleTheme}
          aria-label={themeLabel}
          title={themeLabel}
          className="text-stone-400 dark:text-stone-500 hover:text-stone-700 dark:hover:text-stone-300 transition-colors"
        >
          {theme === 'dark' ? (
            <MoonIcon className="size-5" />
          ) : theme === 'light' ? (
            <SunIcon className="size-5" />
          ) : (
            <ComputerDesktopIcon className="size-5" />
          )}
        </button>

        {!loading && (
          session ? (
            <>
              <Link
                to="/publish"
                className="flex items-center gap-1.5 rounded-md bg-stone-900 dark:bg-stone-100 px-3 py-1.5 text-xs font-semibold text-stone-50 dark:text-stone-900 hover:bg-stone-700 dark:hover:bg-stone-200 transition-colors"
              >
                <PencilSquareIcon className="size-3.5" />
                Write
              </Link>
              <Link
                to={`/${encodeURIComponent(session.sub)}`}
                aria-label="Your profile"
                title="Your public profile"
                className="block rounded-full hover:opacity-75 transition-opacity"
              >
                <Avatar
                  src={avatarUrl}
                  alt="Your avatar"
                  className="size-7"
                  fallback={<UserCircleIcon className="size-7 text-stone-500 dark:text-stone-400" />}
                />
              </Link>
            </>
          ) : (
            <Link
              to="/"
              className="text-sm text-stone-500 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200 transition-colors"
            >
              Sign in
            </Link>
          )
        )}
      </div>
    </nav>
  )
}
