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

export function UserListScreen() {
  const { navigate, back } = useNavigation();
  const { users, loading, error, fetchUsers, clearError } = useUsers();
  const [selectedIndex, setSelectedIndex] = useState(0);

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

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

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

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

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

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

      {!loading && !error && (
        <UserTable users={users} selectedIndex={selectedIndex} />
      )}

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