import React, {
  useContext,
  createContext,
  useState,
  ReactNode,
  useEffect,
} from "react";
import { Box, Text } from "./Ink";

type Shortcut =
  | "upArrow"
  | "rightArrow"
  | "downArrow"
  | "leftArrow"
  | "return"
  | "space";

type KeyboardShortcut = {
  name: string;
  key: Shortcut;
};

export const KeyboardShortcutsContext = createContext<{
  shortcuts: Array<KeyboardShortcut>;
  setShortcuts: (shortcuts: Array<KeyboardShortcut>) => void;
}>({ shortcuts: [], setShortcuts: () => {} });

const shortcutToCharacter = (shortcut: Shortcut): string => {
  switch (shortcut) {
    case "upArrow":
      return "↑";
    case "rightArrow":
      return "→";
    case "downArrow":
      return "↓";
    case "leftArrow":
      return "←";
    case "return":
      return "↲";
    case "space":
      return "␣";
  }
};

export const useKeyboardShortcuts = (
  shortcuts: Partial<Record<Shortcut, { name: string }>>,
) => {
  const { setShortcuts } = useContext(KeyboardShortcutsContext);

  useEffect(() => {
    setShortcuts(
      (Object.entries(shortcuts) as Array<[Shortcut, { name: string }]>).map(
        ([key, { name }]) => ({ key, name }),
      ),
    );
  }, [JSON.stringify(shortcuts)]);
};

export const KeyboardShortcuts = () => {
  const { shortcuts } = useContext(KeyboardShortcutsContext);

  return (
    <Box gap={3}>
      {shortcuts.map(({ name, key }) => (
        <Text key={`${key}-${name}`}>
          {shortcutToCharacter(key)} {name}
        </Text>
      ))}
    </Box>
  );
};

export const KeyboardShortcutsProvider = ({
  children,
}: {
  children: ReactNode;
}) => {
  const [shortcuts, setShortcuts] = useState<Array<KeyboardShortcut>>([]);

  return (
    <KeyboardShortcutsContext value={{ shortcuts, setShortcuts }}>
      {children}
    </KeyboardShortcutsContext>
  );
};
