/**
 * Menubar for the canvas page: Project (Import/Export), Edit (Undo/Redo), View (Fit View, Theme).
 */

import React, { useEffect, useMemo } from 'react'
import { Link, useParams } from 'react-router-dom'
import {
  Menubar,
  MenubarContent,
  MenubarItem,
  MenubarMenu,
  MenubarSeparator,
  MenubarTrigger,
  MenubarSub,
  MenubarSubTrigger,
  MenubarSubContent,
  MenubarCheckboxItem,
} from '@/components/ui/menubar'
import { Kbd, KbdGroup } from '@/components/ui/kbd'
import { useTheme } from '@/lib/themeContext'
import { usePlatform } from '@/app/platform/platformContext'
import { ArrowLeft, Download, FolderOpen, Moon, Redo2, Sun, Undo2 } from 'lucide-react'

export type CanvasMenubarProps = {
  onImport: () => void
  onExport: () => void
  undo: () => void
  redo: () => void
  canUndo: boolean
  canRedo: boolean
  onFitView?: () => void
}

const UNDO_KEYS = { key: 'z', shiftKey: false }
const REDO_KEYS = { key: 'z', shiftKey: true }

function matchKey(ev: KeyboardEvent, want: { key: string; shiftKey: boolean }) {
  const mod = ev.ctrlKey || ev.metaKey
  return ev.key.toLowerCase() === want.key && !!mod && !!ev.shiftKey === want.shiftKey
}

export function CanvasMenubar({
  onImport,
  onExport,
  undo,
  redo,
  canUndo,
  canRedo,
  onFitView,
}: CanvasMenubarProps) {
  const { theme, setTheme } = useTheme()
  const { projectId } = useParams<{ projectId: string }>()
  const { projects } = usePlatform()
  const projectName = useMemo(
    () => (projectId ? projects.find((p) => p.id === projectId)?.name ?? null : null),
    [projectId, projects]
  )

  useEffect(() => {
    const onKeyDown = (ev: KeyboardEvent) => {
      if (matchKey(ev, UNDO_KEYS)) {
        if (canUndo) {
          ev.preventDefault()
          ev.stopPropagation()
          undo()
        }
        return
      }
      if (matchKey(ev, REDO_KEYS)) {
        if (canRedo) {
          ev.preventDefault()
          ev.stopPropagation()
          redo()
        }
      }
    }
    window.addEventListener('keydown', onKeyDown, true)
    return () => window.removeEventListener('keydown', onKeyDown, true)
  }, [undo, redo, canUndo, canRedo])

  return (
    <div className="relative flex h-9 w-full shrink-0 items-center border-b border-border/40 bg-background">
      <Menubar className="flex-1 shrink-0 rounded-none border-0 border-b-0 bg-transparent p-0 shadow-none">
        <Link
          to="/projects"
          aria-label="Back to projects"
          className="flex shrink-0 items-center rounded-sm px-2 py-1 ml-1 text-sm outline-none focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground"
        >
          <ArrowLeft className="size-4" />
        </Link>
        <MenubarMenu>
          <MenubarTrigger className="font-medium">Project</MenubarTrigger>
          <MenubarContent>
            <MenubarItem onClick={onImport} className="gap-2">
              <FolderOpen className="h-4 w-4" />
              Import…
            </MenubarItem>
            <MenubarItem onClick={onExport} className="gap-2">
              <Download className="h-4 w-4" />
              Export…
            </MenubarItem>
          </MenubarContent>
        </MenubarMenu>
        <MenubarMenu>
          <MenubarTrigger className="font-medium">Edit</MenubarTrigger>
          <MenubarContent>
            <MenubarItem onClick={undo} disabled={!canUndo} className="gap-2">
              <Undo2 className="h-4 w-4" />
              Undo
              <span className="ml-auto pl-4">
                <KbdGroup>
                  <Kbd>⌘ + Z</Kbd>
                </KbdGroup>
              </span>
            </MenubarItem>
            <MenubarItem onClick={redo} disabled={!canRedo} className="gap-2">
              <Redo2 className="h-4 w-4" />
              Redo
              <span className="ml-auto pl-4">
                <KbdGroup>
                  <Kbd>⌘ + ⇧ + Z</Kbd>
                </KbdGroup>
              </span>
            </MenubarItem>
          </MenubarContent>
        </MenubarMenu>
        <MenubarMenu>
          <MenubarTrigger className="font-medium">View</MenubarTrigger>
          <MenubarContent>
            {onFitView && (
              <MenubarItem onClick={onFitView} className="gap-2">
                Fit View
                <span className="ml-auto pl-4">
                  <KbdGroup>
                    <Kbd>⌘0</Kbd>
                  </KbdGroup>
                </span>
              </MenubarItem>
            )}
            {onFitView && <MenubarSeparator />}
            <MenubarSub>
              <MenubarSubTrigger>Theme</MenubarSubTrigger>
              <MenubarSubContent>
                <MenubarCheckboxItem
                  checked={theme === 'light'}
                  onCheckedChange={() => setTheme('light')}
                  className="gap-2"
                >
                  <Sun className="h-4 w-4" />
                  Light
                </MenubarCheckboxItem>
                <MenubarCheckboxItem
                  checked={theme === 'dark'}
                  onCheckedChange={() => setTheme('dark')}
                  className="gap-2"
                >
                  <Moon className="h-4 w-4" />
                  Dark
                </MenubarCheckboxItem>
              </MenubarSubContent>
            </MenubarSub>
          </MenubarContent>
        </MenubarMenu>
      </Menubar>
      {projectName && (
        <span className="pointer-events-none absolute left-1/2 -translate-x-1/2 truncate max-w-[40%] text-sm font-medium text-foreground">
          {projectName}
        </span>
      )}
    </div>
  )
}
