import React, { useEffect } from 'react';
import { Box } from 'ink';
import { AuthProvider, useAuth } from './state/auth-context.js';
import { NavigationProvider, useNavigation } from './state/navigation-context.js';
import { LoginScreen } from './components/auth/LoginScreen.js';
import { MainMenu } from './components/MainMenu.js';
import { MainLayout } from './components/layout/MainLayout.js';
import { LoadingSpinner } from './components/shared/LoadingSpinner.js';
import { UserListScreen } from './components/users/UserListScreen.js';
import { UserCreateScreen } from './components/users/UserCreateScreen.js';
import { UserDetailScreen } from './components/users/UserDetailScreen.js';
import { ChangePasswordScreen } from './components/users/ChangePasswordScreen.js';
import { RoleListScreen } from './components/roles/RoleListScreen.js';
import { RoleDetailScreen } from './components/roles/RoleDetailScreen.js';

function ScreenRouter() {
  const { isAuthenticated, loading } = useAuth();
  const { current, navigate } = useNavigation();

  // Redirect zu main-menu nach erfolgreichem Login
  useEffect(() => {
    if (isAuthenticated && current === 'login') {
      navigate('main-menu');
    }
  }, [isAuthenticated, current, navigate]);

  if (loading) {
    return (
      <Box alignItems="center" justifyContent="center" paddingY={4}>
        <LoadingSpinner label="Initialisiere..." />
      </Box>
    );
  }

  if (!isAuthenticated) {
    return (
      <MainLayout showHeader={false}>
        <LoginScreen />
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      {current === 'main-menu' && <MainMenu />}
      {current === 'user-list' && <UserListScreen />}
      {current === 'user-create' && <UserCreateScreen />}
      {current === 'user-detail' && <UserDetailScreen />}
      {current === 'change-password' && <ChangePasswordScreen />}
      {current === 'role-list' && <RoleListScreen />}
      {current === 'role-detail' && <RoleDetailScreen />}
    </MainLayout>
  );
}

export function App() {
  return (
    <NavigationProvider initialScreen="login">
      <AuthProvider>
        <ScreenRouter />
      </AuthProvider>
    </NavigationProvider>
  );
}
