import { useState } from "react";
import { ArrowFatLineUp, Backspace, CaretDown, Command } from "@phosphor-icons/react";

type Shortcut = {
  keys: string[];
  label: string;
};

const shortcuts: Shortcut[] = [
  { keys: ["S"], label: "Select" },
  { keys: ["B"], label: "Brush" },
  { keys: ["E"], label: "Eraser" },
  { keys: ["K"], label: "Chroma key" },
  { keys: ["P"], label: "Pan" },
  { keys: ["Space"], label: "Hold to pan" },
  { keys: ["L"], label: "Layers" },
  { keys: ["⌘", "O"], label: "Open image" },
  { keys: ["⌘", "Z"], label: "Undo" },
  { keys: ["⇧", "⌘", "Z"], label: "Redo" },
  { keys: ["Del", "⌫"], label: "Delete" },
];

export function ShortcutsDisplay() {
  const [open, setOpen] = useState(true);

  return (
    <aside
      aria-label="Keyboard shortcuts"
      className="pointer-events-auto hidden w-[30rem] rounded-[2rem] p-3 text-white backdrop-blur-xl sm:block"
    >
      <button
        type="button"
        className="flex h-12 w-full items-center justify-between rounded-full px-5 text-left transition hover:bg-white/5 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/30"
        aria-expanded={open}
        onClick={() => setOpen((current) => !current)}
      >
        <span className="text-[0.65rem] font-semibold uppercase tracking-[0.22em] text-white/45">Shortcuts</span>
        <CaretDown size={14} className={`text-white/40 transition-transform ${open ? "rotate-0" : "-rotate-90"}`} weight="bold" />
      </button>
      <dl className={`mt-2 grid grid-cols-2 gap-x-4 gap-y-1 overflow-hidden rounded-[1.5rem] transition-all duration-200 ${open ? "max-h-96 p-1 opacity-100" : "mt-0 max-h-0 p-0 opacity-0"}`}>
        {shortcuts.map((shortcut) => (
          <div key={`${shortcut.keys.join("+")}-${shortcut.label}`} className="flex h-8 items-center justify-between gap-3 rounded-full px-2">
            <dt className="truncate text-xs font-medium text-white/60">{shortcut.label}</dt>
            <dd className="flex shrink-0 items-center gap-2">
              {shortcut.keys.map((key, index) => (
                <span key={key} className="inline-flex items-center gap-2">
                  {shortcut.label === "Delete" && index > 0 ? <span className="h-3 w-px bg-white/20" aria-hidden="true" /> : null}
                  <kbd className="inline-flex h-8 min-w-8 items-center justify-center rounded-full bg-white/5 px-3 text-sm font-semibold leading-none text-white/75">
                    {keyIcon(key) ?? key}
                  </kbd>
                </span>
              ))}
            </dd>
          </div>
        ))}
      </dl>
    </aside>
  );
}

function keyIcon(key: string) {
  switch (key) {
    case "⌘":
      return <Command size={18} weight="bold" />;
    case "⇧":
      return <ArrowFatLineUp size={18} weight="bold" />;
    case "⌫":
      return <Backspace size={18} weight="bold" />;
    default:
      return undefined;
  }
}
