'use client'

import { useState, type ReactNode } from 'react'
import { Search, User, ChevronDown, Menu, Sun, Moon } from 'lucide-react'
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { CommandPalette } from '../components/CommandPalette.js'
import { NotificationBell } from '../components/NotificationBell.js'
import { useTheme } from '../components/ThemeProvider.js'
import { LocaleSwitcher } from '../components/LocaleSwitcher.js'

export interface HeaderProps {
  onToggleSidebar: () => void
  session?: any
  onNavigate: (path: string) => void
  /**
   * Page-specific actions rendered on the far right of the top bar
   * (after the search input + utility icons). Used to surface
   * dashboard-level primary actions like "+ New Post" / "View Site"
   * without forcing every view to render its own header.
   *
   * The Layout decides what to pass here based on `currentPath`.
   * Keeping the slot on Header rather than per-view means the
   * actions row stays consistent across navigation and never reflows
   * on view-change.
   */
  pageActions?: ReactNode
  /** Signs the user out (revokes the server session + clears local state). */
  onLogout?: () => void
}

export function Header({
  onToggleSidebar,
  session,
  onNavigate,
  onLogout,
  pageActions,
}: HeaderProps) {
  const [showCommandPalette, setShowCommandPalette] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const { resolvedTheme, setTheme } = useTheme()

  const toggleTheme = () => {
    setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')
  }

  const initial =
    session?.user?.name?.charAt(0)?.toUpperCase() ??
    session?.user?.email?.charAt(0)?.toUpperCase() ??
    'A'

  return (
    <>
      <header className="border-border bg-background flex h-14 items-center gap-3 border-b px-4">
        <button
          onClick={onToggleSidebar}
          className="hover:bg-accent rounded-lg p-2 transition-colors md:hidden"
          aria-label="Toggle sidebar"
        >
          <Menu className="text-foreground h-5 w-5" strokeWidth={2} />
        </button>

        {/* Search: takes available width on desktop so it visually anchors
            the top bar like the reference design. */}
        <div className="relative hidden flex-1 md:block">
          <Search
            className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"
            aria-hidden
          />
          <input
            type="text"
            placeholder="Search..."
            aria-label="Search content"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onFocus={() => setShowCommandPalette(true)}
            onKeyDown={(e) => {
              if (e.key === 'Escape') (e.target as HTMLInputElement).blur()
            }}
            className="border-border bg-input-background text-foreground placeholder:text-muted-foreground focus:ring-ring h-9 w-full max-w-md rounded-lg border py-1.5 pr-14 pl-9 text-sm focus:border-transparent focus:ring-2 focus:outline-none"
          />
          {/* Keyboard hint pill. Hidden on narrow widths to avoid overlap. */}
          <span
            className="border-border bg-background text-muted-foreground pointer-events-none absolute top-1/2 right-2 hidden -translate-y-1/2 rounded border px-1.5 py-0.5 font-mono text-[10px] sm:inline-flex"
            aria-hidden
          >
            ⌘K
          </span>
        </div>

        {/* Mobile search trigger (icon-only). */}
        <button
          onClick={() => setShowCommandPalette(true)}
          className="hover:bg-accent rounded-lg p-2 transition-colors md:hidden"
          aria-label="Search"
        >
          <Search className="text-muted-foreground h-5 w-5" />
        </button>

        <div className="ml-auto flex items-center gap-1.5">
          <LocaleSwitcher />

          <button
            onClick={toggleTheme}
            className="hover:bg-accent rounded-lg p-2 transition-colors"
            aria-label={resolvedTheme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
          >
            {resolvedTheme === 'dark' ? (
              <Sun className="text-muted-foreground h-5 w-5" />
            ) : (
              <Moon className="text-muted-foreground h-5 w-5" />
            )}
          </button>

          {/* Real notification bell — replaces the previous inert decoration.
              Renders its own dropdown panel, SSE-backed unread counter, and
              click-to-mark-read flow. */}
          <NotificationBell />

          <DropdownMenu.Root>
            <DropdownMenu.Trigger asChild>
              <button
                className="hover:bg-accent flex items-center gap-1.5 rounded-lg p-1 transition-colors"
                aria-label="Account menu"
              >
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-linear-to-br from-blue-500 to-purple-600">
                  <span className="text-sm font-medium text-white">{initial}</span>
                </div>
                <ChevronDown
                  className="text-muted-foreground hidden h-4 w-4 sm:block"
                  aria-hidden
                />
              </button>
            </DropdownMenu.Trigger>

            <DropdownMenu.Portal>
              <DropdownMenu.Content
                className="bg-popover text-popover-foreground border-border z-50 min-w-[200px] rounded-lg border p-1 shadow-lg"
                align="end"
                sideOffset={5}
              >
                <div className="border-border border-b px-3 py-2">
                  <p className="text-sm font-medium">{session?.user?.name ?? 'Admin User'}</p>
                  <p className="text-muted-foreground text-xs">
                    {session?.user?.email ?? 'admin@example.com'}
                  </p>
                </div>
                <DropdownMenu.Item
                  className="hover:bg-accent flex cursor-pointer items-center gap-2 rounded px-3 py-2 text-sm outline-none"
                  onSelect={() => onNavigate('/profile')}
                >
                  <User className="h-4 w-4" />
                  Profile
                </DropdownMenu.Item>
                <DropdownMenu.Item
                  className="hover:bg-accent flex cursor-pointer items-center gap-2 rounded px-3 py-2 text-sm outline-none"
                  onSelect={() => onNavigate('/settings')}
                >
                  Settings
                </DropdownMenu.Item>
                <DropdownMenu.Separator className="bg-border my-1 h-px" />
                <DropdownMenu.Item
                  className="text-destructive hover:bg-accent flex cursor-pointer items-center gap-2 rounded px-3 py-2 text-sm outline-none"
                  onSelect={() => onLogout?.()}
                >
                  Logout
                </DropdownMenu.Item>
              </DropdownMenu.Content>
            </DropdownMenu.Portal>
          </DropdownMenu.Root>

          {/* Page actions slot — sits to the right of the utility icons so
              the primary CTA is the rightmost element, mirroring the
              reference. Hidden on mobile because narrow viewports lack the
              room; pages can re-surface the same action in their hero
              there. */}
          {pageActions && (
            <div className="border-border ml-2 hidden items-center gap-2 border-l pl-3 md:flex">
              {pageActions}
            </div>
          )}
        </div>
      </header>

      <CommandPalette
        open={showCommandPalette}
        onOpenChange={setShowCommandPalette}
        onNavigate={onNavigate}
      />
    </>
  )
}
