import { type ReactNode } from 'react'
import { Moon, Sun, Power } from 'lucide-react'
import styles from './TopBar.module.css'
import { Breadcrumb } from '../../composites/Breadcrumb/Breadcrumb'
import { Dropdown } from '../../composites/Dropdown/Dropdown'
import { Avatar } from '../../primitives/Avatar/Avatar'
import { useTheme } from '../../providers/ThemeProvider'
import { useBreadcrumbOverride } from '../../providers/BreadcrumbProvider'
import type { BreadcrumbItem } from '../../providers/BreadcrumbProvider'

interface TopBarProps {
  breadcrumb: BreadcrumbItem[]
  environment?: ReactNode
  user?: { name: string }
  userMenuItems?: import('../../composites/Dropdown/Dropdown').DropdownItem[]
  onLogout?: () => void
  className?: string
  children?: ReactNode
}

export function TopBar({
  breadcrumb,
  environment,
  user,
  userMenuItems,
  onLogout,
  className,
  children,
}: TopBarProps) {
  const { theme, toggleTheme } = useTheme()
  const breadcrumbOverride = useBreadcrumbOverride()

  return (
    <header className={`${styles.topbar} ${className ?? ''}`}>
      {/* Left: Breadcrumb */}
      <Breadcrumb items={breadcrumbOverride ?? breadcrumb} className={styles.breadcrumb} />

      {/* Center: consumer-provided controls */}
      {children}

      {/* Right: theme toggle, env badge, user */}
      <div className={styles.right}>
        <button
          className={styles.themeToggle}
          onClick={toggleTheme}
          type="button"
          aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
          title={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
        >
          {theme === 'light' ? <Moon size={16} /> : <Sun size={16} />}
        </button>
        {environment && (
          <div className={styles.env}>{environment}</div>
        )}
        {user && (
          <Dropdown
            trigger={
              <div className={styles.user}>
                <span className={styles.userName}>{user.name}</span>
                <Avatar name={user.name} size="md" />
              </div>
            }
            items={[
              ...(userMenuItems ?? []),
              ...(userMenuItems?.length ? [{ label: '', divider: true }] : []),
              { label: 'Logout', icon: <Power size={14} />, onClick: onLogout },
            ]}
          />
        )}
      </div>
    </header>
  )
}
