import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import type { Screen } from '../../state/navigation-context.js';

interface MenuItem {
  label: string;
  screen: Screen;
  description: string;
}

const MENU_ITEMS: MenuItem[] = [
  { label: 'Rezepte', screen: 'recipe-list', description: 'Rezepte anlegen und verwalten' },
  { label: 'Chargen', screen: 'batch-list', description: 'Produktionschargen planen, starten und abschließen' },
];

export function ProductionMenu() {
  const { navigate, back } = useNavigation();
  const [selectedIndex, setSelectedIndex] = useState(0);

  useInput((_input, key) => {
    if (key.upArrow) setSelectedIndex((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedIndex((i) => Math.min(MENU_ITEMS.length - 1, i + 1));
    if (key.return) {
      const item = MENU_ITEMS[selectedIndex];
      if (item) navigate(item.screen);
    }
    if (key.backspace || key.escape) back();
  });

  return (
    <Box flexDirection="column" paddingY={1}>
      <Box marginBottom={1}>
        <Text color="cyan" bold>Produktion</Text>
      </Box>

      <Box
        flexDirection="column"
        borderStyle="round"
        borderColor="gray"
        paddingX={2}
        paddingY={1}
        width={50}
      >
        {MENU_ITEMS.map((item, index) => (
          <Box key={item.screen} flexDirection="column">
            <Text color={index === selectedIndex ? 'cyan' : 'white'}>
              {index === selectedIndex ? '▶ ' : '  '}
              {item.label}
            </Text>
            {index === selectedIndex && (
              <Box paddingLeft={4}>
                <Text color="gray" dimColor>{item.description}</Text>
              </Box>
            )}
          </Box>
        ))}

        <Box marginTop={1}>
          <Text color="gray" dimColor>↑↓ navigieren · Enter auswählen · Backspace Zurück</Text>
        </Box>
      </Box>
    </Box>
  );
}
