import React, { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import type { RoleDTO } from '@effigenix/api-client';

interface RoleSelectListProps {
  roles: RoleDTO[];
  label: string;
  onSelect: (role: RoleDTO) => void;
  onCancel: () => void;
}

export function RoleSelectList({ roles, label, onSelect, onCancel }: RoleSelectListProps) {
  const [selectedIndex, setSelectedIndex] = useState(0);

  useInput((_input, key) => {
    if (roles.length === 0) {
      if (key.escape) onCancel();
      return;
    }
    if (key.upArrow) {
      setSelectedIndex((i) => Math.max(0, i - 1));
    } else if (key.downArrow) {
      setSelectedIndex((i) => Math.min(roles.length - 1, i + 1));
    } else if (key.return) {
      const role = roles[selectedIndex];
      if (role !== undefined) onSelect(role);
    } else if (key.escape) {
      onCancel();
    }
  });

  return (
    <Box flexDirection="column" borderStyle="round" borderColor="cyan" paddingX={1}>
      <Text color="cyan" bold>
        {label}
      </Text>
      {roles.length === 0 ? (
        <Text color="gray" dimColor>
          Keine Rollen verfügbar.
        </Text>
      ) : (
        roles.map((role, index) => (
          <Text key={role.id} color={index === selectedIndex ? 'cyan' : 'white'}>
            {index === selectedIndex ? '▶ ' : '  '}
            {role.name}
          </Text>
        ))
      )}
      <Text color="gray" dimColor>
        ↑↓ navigieren · Enter auswählen · Escape abbrechen
      </Text>
    </Box>
  );
}
