import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog'
import {
    formatKeyBinding,
    SHORTCUT_DEFINITIONS,
    SHORTCUT_SCOPE_LABELS,
} from '@/lib/keyboardShortcuts'

import type {
    KeyBinding,
    ShortcutActionId,
    ShortcutScope,
} from '@/lib/keyboardShortcuts'
import type { FC } from 'react'

type Props = {
    open:               boolean
    onOpenChange:       (open: boolean) => void
    activeScope:        ShortcutScope
    effectiveBindings:  Record<ShortcutActionId, KeyBinding | null>
    conflictActionIds:  Set<ShortcutActionId>
    availableActionIds: Set<ShortcutActionId>
}


const ShortcutHelpDialog: FC<Props> = (
    {
	open,
	onOpenChange,
	activeScope,
	effectiveBindings,
	conflictActionIds,
	availableActionIds,
    },
) => {
  const rows = SHORTCUT_DEFINITIONS
      .filter (definition =>
	  definition.scope === 'global' || definition.scope === activeScope)
      .filter (definition => availableActionIds.has (definition.id))

  return (
      <Dialog open={open} onOpenChange={onOpenChange}>
	<DialogContent className="max-w-3xl px-6 pb-6 pt-7">
	  <DialogHeader className="pl-8">
	    <DialogTitle>キーボード・ショートカット</DialogTitle>
	    <DialogDescription>
	      この画面で利用できるショートカットを表示します。
	    </DialogDescription>
	  </DialogHeader>

	  <div className="overflow-x-auto">
	    <table className="w-full min-w-[40rem] table-fixed border-collapse text-sm">
	      <thead className="border-b border-border">
		<tr>
		  <th className="p-2 text-left">操作</th>
		  <th className="p-2 text-left">適用範囲</th>
		  <th className="p-2 text-left">キー</th>
		  <th className="p-2 text-left">競合</th>
		</tr>
	      </thead>
	      <tbody>
		{rows.map (row => (
		    <tr key={row.id} className="border-b border-border/60 last:border-b-0">
		      <td className="p-2">{row.label}</td>
		      <td className="p-2">{SHORTCUT_SCOPE_LABELS[row.scope]}</td>
		      <td className="p-2 font-mono">
			{formatKeyBinding (effectiveBindings[row.id])}
		      </td>
		      <td className="p-2">
			{conflictActionIds.has (row.id)
			 ? <span className="text-red-600 dark:text-red-400">競合あり</span>
			 : 'なし'}
		      </td>
		    </tr>))}
	      </tbody>
	    </table>
	  </div>
	</DialogContent>
      </Dialog>)
}

export default ShortcutHelpDialog
