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: 'Lagerorte', screen: 'storage-location-list', description: 'Lagerorte verwalten (Kühlräume, Trockenlager, …)' },
  { label: 'Bestände', screen: 'stock-list', description: 'Bestände einsehen, anlegen und Chargen verwalten' },
  { label: 'Bestandsbewegungen', screen: 'stock-movement-list', description: 'Wareneingänge, Verbräuche, Korrekturen und Umlagerungen' },
  { label: 'Charge einbuchen', screen: 'stock-batch-entry', description: 'Neue Charge in einen Bestand einbuchen' },
  { label: 'Inventuren', screen: 'inventory-count-list', description: 'Inventuren anlegen, zählen und abschließen' },
];

export function InventoryMenu() {
  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>Lagerverwaltung</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>
  );
}
