import React, { useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { useRoles } from '../../hooks/useRoles.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { RoleTable } from './RoleTable.js';

export function RoleListScreen() {
  const { navigate, back } = useNavigation();
  const { roles, loading, error, fetchRoles, clearError } = useRoles();
  const [selectedIndex, setSelectedIndex] = useState(0);

  useEffect(() => {
    void fetchRoles();
  }, [fetchRoles]);

  useInput((_input, key) => {
    if (loading) return;

    if (key.upArrow) {
      setSelectedIndex((i) => Math.max(0, i - 1));
    }
    if (key.downArrow) {
      setSelectedIndex((i) => Math.min(roles.length - 1, i + 1));
    }
    if (key.return && roles.length > 0) {
      const role = roles[selectedIndex];
      if (role) {
        navigate('role-detail', { roleId: role.id });
      }
    }
    if (key.backspace || key.escape) {
      back();
    }
  });

  return (
    <Box flexDirection="column" gap={1}>
      <Box>
        <Text color="cyan" bold>
          Rollenverwaltung
        </Text>
        <Text color="gray" dimColor>
          {' '}– {roles.length} Rollen
        </Text>
      </Box>

      {loading && <LoadingSpinner label="Lade Rollen..." />}

      {error && !loading && (
        <ErrorDisplay message={error} onDismiss={clearError} />
      )}

      {!loading && !error && (
        <RoleTable roles={roles} selectedIndex={selectedIndex} />
      )}

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