import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'

import { AppHeaderView } from '~/components/layout/app-header-view'
import { CHROME_COLLAPSED_SIDEBAR_WIDTH } from '~/components/layout/layout-responsive'
import { useChatSessionLayoutRecord } from '~/components/layout/use-layout-query-records'
import { SessionExecutionChrome } from '~/features/remote-hosts/session-execution-chrome'
import { SessionIsolationChrome } from '~/features/session/session-isolation-chrome'
import { SessionPullRequestChrome } from '~/features/session/session-pull-request-chrome'
import { WorkHeaderChrome } from '~/features/work/work-header-chrome'
import { isTearoffWindow, windowControlsSafeArea } from '~/lib/electron'
import { useActiveSurface } from '~/navigation/active-surface'
import { SurfaceBar } from '~/navigation/surface-bar'
import { chatSessionIdForSurface, workIdForSurface } from '~/navigation/surface-identity'
import { useBrowserPanelStore } from '~/store/browser-panel'
import { useLayoutStore } from '~/store/layout'

interface AppHeaderProps {
  hasAside?: boolean
  hasBrowserPanel?: boolean
  hasPanel?: boolean
  browserPanelOwnerId?: string | null
  browserPanelOpen?: boolean
  sessionScoped?: boolean
  headerActions?: React.ReactNode
  sidebarInSheet?: boolean
  sidebarSheetOpen?: boolean
  onOpenSidebarSheet?: () => void
  onToggleSidebarSheet?: () => void
}

export function AppHeader({
  hasAside = false,
  hasBrowserPanel = false,
  hasPanel = false,
  browserPanelOwnerId = null,
  browserPanelOpen = false,
  sessionScoped = false,
  headerActions,
  sidebarInSheet = false,
  sidebarSheetOpen = false,
  onOpenSidebarSheet,
  onToggleSidebarSheet,
}: AppHeaderProps) {
  'use no memo'
  const { t } = useTranslation('chrome')
  const { t: tWorkspace } = useTranslation('workspace')
  const bottomPanelOpen = useLayoutStore(s => s.bottomPanelOpen)
  const asideOpen = useLayoutStore(s => s.asideOpen)
  const toggleBottomPanel = useLayoutStore(s => s.toggleBottomPanel)
  const toggleAside = useLayoutStore(s => s.toggleAside)
  const sidebarCollapsed = useLayoutStore(s => s.sidebarCollapsed)
  const toggleSidebar = useLayoutStore(s => s.toggleSidebar)
  const toggleBrowserPanel = useBrowserPanelStore(s => s.toggleDock)
  const activeSurface = useActiveSurface()
  const activeWorkId = workIdForSurface(activeSurface)
  const isSettingsActive = activeSurface?.kind === 'settings'
  const isDrillIn = isSettingsActive
  const sidebarToggleLabel = sidebarInSheet
    ? sidebarSheetOpen
      ? t('header.action.closeSidebar')
      : t('header.action.openSidebar')
    : sidebarCollapsed
      ? t('header.action.expandSidebar')
      : t('header.action.collapseSidebar')
  const reserveLeftWindowControls = windowControlsSafeArea.side === 'left'
    && windowControlsSafeArea.width > 0
    && (isTearoffWindow || sidebarInSheet)
  const reserveRightWindowControls = windowControlsSafeArea.side === 'right'
    && windowControlsSafeArea.width > 0
  const collapsedSidebarWindowControlsOffset = !sidebarInSheet
    && sidebarCollapsed
    && windowControlsSafeArea.side === 'left'
    ? Math.max(0, windowControlsSafeArea.width - CHROME_COLLAPSED_SIDEBAR_WIDTH - 2)
    : 0
  // In a tear-off window the surface is router-driven (navigated to the torn-off
  // route), so derive the chat session id from the active surface rather than
  // from a window env flag.
  const scopedSessionId = sessionScoped ? chatSessionIdForSurface(activeSurface) : null
  const scopedSessionLayout = useChatSessionLayoutRecord(scopedSessionId)
  const activeChatTitle = scopedSessionId && activeSurface?.kind === 'chat' ? activeSurface.title : null
  const sessionScopedTitle = scopedSessionLayout?.sessionTitle || activeChatTitle || tWorkspace('session.fallbackTitle')

  const handleSidebarToggle = useCallback(() => {
    if (sidebarInSheet) {
      if (onToggleSidebarSheet) {
        onToggleSidebarSheet()
        return
      }
      onOpenSidebarSheet?.()
      return
    }

    toggleSidebar()
  }, [onOpenSidebarSheet, onToggleSidebarSheet, sidebarInSheet, toggleSidebar])

  const handleAsideToggle = useCallback(() => {
    toggleAside()
  }, [toggleAside])

  return (
    <AppHeaderView
      isDrillIn={isDrillIn}
      isTearoffWindow={isTearoffWindow}
      sidebar={{
        inSheet: sidebarInSheet,
        sheetOpen: sidebarSheetOpen,
        collapsed: sidebarCollapsed,
        toggleLabel: sidebarToggleLabel,
        collapsedWindowControlsOffset: collapsedSidebarWindowControlsOffset,
        onToggle: handleSidebarToggle,
      }}
      windowControls={{
        leftReservedWidth: reserveLeftWindowControls ? windowControlsSafeArea.width : 0,
        rightReservedWidth: reserveRightWindowControls ? windowControlsSafeArea.width : 0,
      }}
      surface={sessionScoped
        ? (
            <div className="flex h-full min-w-0 items-center gap-2">
              <div
                className="min-w-0 truncate px-2 text-[13px] font-medium text-foreground"
                title={sessionScopedTitle}
              >
                {sessionScopedTitle}
              </div>
              {scopedSessionId && (
                <>
                  <SessionExecutionChrome sessionId={scopedSessionId} />
                  <SessionIsolationChrome
                    sessionId={scopedSessionId}
                    workspaceId={scopedSessionLayout?.workspaceId ?? null}
                  />
                  <SessionPullRequestChrome sessionId={scopedSessionId} />
                </>
              )}
            </div>
          )
        : <SurfaceBar className="h-full" />}
      actions={(
        <>
          {headerActions}
          {activeWorkId && <WorkHeaderChrome workId={activeWorkId} />}
        </>
      )}
      browserPanel={!isSettingsActive && hasBrowserPanel
        ? {
            label: t('header.action.toggleBrowserPanel'),
            open: browserPanelOpen,
            onToggle: () => toggleBrowserPanel(browserPanelOwnerId),
          }
        : null}
      bottomPanel={!isSettingsActive && hasPanel
        ? {
            label: t('header.action.toggleBottomPanel'),
            open: bottomPanelOpen,
            onToggle: toggleBottomPanel,
          }
        : null}
      aside={!isSettingsActive && hasAside
        ? {
            label: t('header.action.toggleRightPanel'),
            open: asideOpen,
            onToggle: handleAsideToggle,
          }
        : null}
    />
  )
}
