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: 'Produktkategorien', screen: 'category-list', description: 'Kategorien verwalten' },
  { label: 'Lieferanten', screen: 'supplier-list', description: 'Lieferanten, Zertifikate, Bewertungen' },
  { label: 'Artikel', screen: 'article-list', description: 'Artikel und Verkaufseinheiten' },
  { label: 'Kunden', screen: 'customer-list', description: 'Kunden, Lieferadressen, Präferenzen' },
];

export function MasterdataMenu() {
  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>Stammdaten</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" marginBottom={index < MENU_ITEMS.length - 1 ? 0 : 0}>
            <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>
  );
}
