import { IconButton } from '@overdeck/deck-ui'
import { DASHBOARD_MAIN_ID } from '@platform-modules/ui-primitives'
import { useEffect, useState, type ReactNode } from 'react'
import { Sidebar } from './Sidebar'
import { HealthStatusChip } from './health/HealthStatusChip'

export interface DeckShellProps {
  activePath: string
  pageTitle: string
  children: ReactNode
}

function MenuIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
      <path d="M2 3.25h12v1.5H2v-1.5Zm0 4.25h12v1.5H2v-1.5Zm0 4.25h12v1.5H2v-1.5Z" />
    </svg>
  )
}

function CloseIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
      <path d="M3.47 3.47 8 7.999l4.53-4.53 1.06 1.06L9.06 9.06l4.53 4.53-1.06 1.06L8 10.12l-4.53 4.53-1.06-1.06 4.53-4.53-4.53-4.53 1.06-1.06Z" />
    </svg>
  )
}

function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState(false)
  useEffect(() => {
    const media = window.matchMedia(query)
    const update = () => setMatches(media.matches)
    update()
    media.addEventListener('change', update)
    return () => media.removeEventListener('change', update)
  }, [query])
  return matches
}

/** App chrome — max-width shell, sliding mobile nav, desktop sidebar pinned left. */
export function DeckShell({ activePath, pageTitle, children }: DeckShellProps) {
  const [mobileNavOpen, setMobileNavOpen] = useState(false)
  const desktopNav = useMediaQuery('(min-width: 768px)')

  useEffect(() => {
    if (!mobileNavOpen) return
    const previousOverflow = document.body.style.overflow
    document.body.style.overflow = 'hidden'
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setMobileNavOpen(false)
    }
    window.addEventListener('keydown', onKeyDown)
    return () => {
      document.body.style.overflow = previousOverflow
      window.removeEventListener('keydown', onKeyDown)
    }
  }, [mobileNavOpen])

  return (
    <div className="deck-shell-outer min-h-dvh bg-[var(--deck-page-bg)] px-0 py-0 md:px-4 md:py-7">
      <a
        href={`#${DASHBOARD_MAIN_ID}`}
        className="sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-[60] focus:rounded-md focus:bg-surface focus:px-3 focus:py-2 focus:text-fg focus:outline focus:outline-accent"
      >
        Skip to main content
      </a>

      <div className="deck-shell mx-auto flex min-h-dvh w-full max-w-[1240px] flex-col bg-bg md:min-h-[calc(100dvh-3.5rem)] md:flex-row md:overflow-hidden md:rounded-[14px] md:border md:border-border md:shadow-[var(--deck-shell-shadow)]">
        {mobileNavOpen ? (
          <button
            type="button"
            aria-label="Close navigation"
            className="fixed inset-0 z-40 bg-[var(--deck-nav-scrim)] md:hidden"
            onClick={() => setMobileNavOpen(false)}
          />
        ) : null}

        <nav
          id="dashboard-sidebar"
          aria-label="Sidebar"
          aria-hidden={!desktopNav && !mobileNavOpen}
          className={
            'fixed inset-y-0 left-0 z-50 w-[min(85vw,240px)] -translate-x-full border-r border-border bg-bg transition-transform duration-200 ease-out md:static md:z-auto md:flex md:w-[198px] md:shrink-0 md:translate-x-0 ' +
            (mobileNavOpen ? 'translate-x-0' : '')
          }
        >
          <div className="flex h-full flex-col">
            <div className="flex items-center justify-between border-b border-border px-2.5 py-2 md:hidden">
              <span className="text-sm font-bold text-fg">Overdeck</span>
              <IconButton icon={<CloseIcon />} label="Close navigation" onClick={() => setMobileNavOpen(false)} />
            </div>
            <Sidebar activePath={activePath} onNavigate={() => setMobileNavOpen(false)} />
          </div>
        </nav>

        <div className="flex min-w-0 flex-1 flex-col">
          <header
            role="banner"
            className="flex items-center gap-2 border-b border-border px-3 py-2.5 md:px-5"
          >
            <div className="md:hidden">
              <IconButton
                icon={<MenuIcon />}
                label="Open navigation"
                onClick={() => setMobileNavOpen(true)}
              />
            </div>
            <div className="flex min-w-0 flex-1 items-center justify-between gap-3">
              <h2 className="truncate text-[15px] font-semibold text-fg">{pageTitle}</h2>
              <HealthStatusChip />
            </div>
          </header>

          <main id={DASHBOARD_MAIN_ID} className="min-w-0 flex-1 overflow-x-hidden px-3 py-4 md:px-5 md:py-[18px]">
            {children}
          </main>
        </div>
      </div>
    </div>
  )
}
