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

interface MenuItem {
  label: string;
  screen?: Screen;
  action?: () => void | Promise<void>;
}

export function MainMenu() {
  const { user, logout } = useAuth();
  const { navigate } = useNavigation();
  const [selectedIndex, setSelectedIndex] = useState(0);

  const items: MenuItem[] = [
    { label: 'Stammdaten', screen: 'masterdata-menu' },
    { label: 'Lagerverwaltung', screen: 'inventory-menu' },
    { label: 'Produktion', screen: 'production-menu' },
    { label: 'Benutzer verwalten', screen: 'user-list' },
    { label: 'Rollen anzeigen', screen: 'role-list' },
    { label: 'Abmelden', action: () => void logout() },
  ];

  useInput((_input, key) => {
    if (key.upArrow) {
      setSelectedIndex((i) => (i > 0 ? i - 1 : items.length - 1));
    }
    if (key.downArrow) {
      setSelectedIndex((i) => (i < items.length - 1 ? i + 1 : 0));
    }
    if (key.return) {
      const item = items[selectedIndex];
      if (item) {
        if (item.screen) {
          navigate(item.screen);
        } else if (item.action) {
          void item.action();
        }
      }
    }
  });

  return (
    <Box flexDirection="column" paddingY={1}>
      <Box marginBottom={1}>
        <Text color="green">Willkommen, </Text>
        <Text color="green" bold>
          {user?.username}
        </Text>
      </Box>

      <Box flexDirection="column" borderStyle="round" borderColor="gray" paddingX={2} paddingY={1} width={40}>
        <Box marginBottom={1}>
          <Text bold>Hauptmenü</Text>
        </Box>

        {items.map((item, index) => (
          <Box key={item.label}>
            <Text color={index === selectedIndex ? 'cyan' : 'white'}>
              {index === selectedIndex ? '▶ ' : '  '}
              {item.label}
            </Text>
          </Box>
        ))}

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