import { useNavigate } from '@solidjs/router'
import { LogOut, Moon, PanelLeft, Sun } from 'lucide-solid'
import { Show } from 'solid-js'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/stores/auth-store'
import { useTheme } from '@/stores/theme-store'

interface TopBarProps {
  pageTitle: string
  pageDescription: string
  onToggleSidebar: () => void
}

export const TopBar = (props: TopBarProps) => {
  const theme = useTheme()
  const auth = useAuth()
  const navigate = useNavigate()

  const logout = (): void => {
    auth.logout()
    navigate('/login', { replace: true })
  }

  const toggleTheme = (): void => {
    const modes = ['dark', 'light', 'system'] as const
    const currentIndex = modes.indexOf(theme.mode())
    const nextIndex = (currentIndex + 1) % modes.length
    theme.setMode(modes[nextIndex])
  }

  return (
    <header class="bg-surface border-b-4 border-primary sticky top-0 z-30 scanlines">
      <div class="flex items-center justify-between gap-4 px-6 py-4">
        <div class="flex items-center gap-4 min-w-0 flex-1">
          <Button
            variant="ghost"
            size="icon"
            class="lg:hidden shrink-0"
            aria-label="Open navigation"
            onClick={props.onToggleSidebar}
          >
            <PanelLeft class="h-6 w-6" />
          </Button>

          <div class="min-w-0">
            <h1 class="text-3xl sm:text-4xl font-bold text-fg truncate uppercase tracking-tighter">{props.pageTitle}</h1>
            <p class="text-xs sm:text-sm text-muted-fg mt-1 truncate uppercase tracking-wider font-mono">{props.pageDescription}</p>
          </div>
        </div>

        <div class="flex items-center gap-2 shrink-0">
          <Show when={theme.mode() === 'dark'}>
            <Button
              variant="ghost"
              size="icon"
              aria-label="Switch to light mode"
              onClick={toggleTheme}
            >
              <Moon class="h-5 w-5" />
            </Button>
          </Show>
          <Show when={theme.mode() === 'light'}>
            <Button
              variant="ghost"
              size="icon"
              aria-label="Switch to system mode"
              onClick={toggleTheme}
            >
              <Sun class="h-5 w-5" />
            </Button>
          </Show>
          <Show when={theme.mode() === 'system'}>
            <Button
              variant="ghost"
              size="icon"
              aria-label="Switch to dark mode"
              onClick={toggleTheme}
            >
              <Sun class="h-5 w-5" />
            </Button>
          </Show>

          <Button 
            variant="danger" 
            size="icon"
            aria-label="Logout" 
            onClick={logout}
          >
            <LogOut class="h-5 w-5" />
          </Button>
        </div>
      </div>
    </header>
  )
}
