import React, { useState, useEffect } from 'react';
import { useAuth } from './hooks/useAuth';
import { useUsers } from './hooks/useUsers';
import { ConfigProvider } from './contexts/ConfigContext';
import Header from './components/common/Header';
import LoginForm from './components/auth/LoginForm';
import PasswordReset from './components/auth/PasswordReset';
import Home from './pages/Home';
import Rules from './pages/Rules';
import Admin from './pages/Admin';
import HandlerLogin from './components/handler/HandlerLogin';
import HandlerDashboard from './components/handler/HandlerDashboard';
import InstallBanner from './components/common/InstallBanner';
import './App.css';

function App() {
  const adminPath = process.env.REACT_APP_ADMIN_PATH || '/verwaltung';
  const resetPasswordPath = '/passwort-zuruecksetzen';
  const isAdminRoute = window.location.pathname === adminPath;
  const isResetPasswordRoute = window.location.pathname === resetPasswordPath;
  const [view, setView] = useState('public');
  const [handlerUser, setHandlerUser] = useState(null);
  const { isAuthenticated, loading: authLoading, login, logout } = useAuth();
  const { users, loading: usersLoading, error, refetch } = useUsers(isAuthenticated);

  const handleLogin = async (username, password) => {
    const result = await login(username, password);
    if (result.success) {
      setView('admin');
      refetch();
    }
    return result;
  };

  const handleLogout = () => {
    logout();
    setView('public');
  };

  const handleHandlerLogin = (userData) => {
    setHandlerUser(userData);
    setView('handler-dashboard');
  };

  const handleHandlerLogout = () => {
    setHandlerUser(null);
    setView('public');
  };

  const handleViewChange = (newView) => {
    setView(newView);
  };

  useEffect(() => {
    if (isAuthenticated) {
      setView('admin');
    }
  }, [isAuthenticated]);

  // Show password reset page if on that route (after all hooks)
  if (isResetPasswordRoute) {
    return <PasswordReset />;
  }

  if (authLoading) {
    return <div className="app-loading">Lädt...</div>;
  }

  return (
    <ConfigProvider>
      <InstallBanner />
      <div className="App">
        {isAuthenticated ? (
          <>
            <Header
              isAdmin={true}
              onLogout={handleLogout}
              currentView={view}
              onViewChange={handleViewChange}
            />
            <main className="app-main">
              {view === 'rules' && <Rules />}
              {view === 'public' && <Home users={users} loading={usersLoading} />}
              {view === 'admin' && (
                <Admin
                  users={users}
                  loading={usersLoading}
                  error={error}
                  onRefetch={refetch}
                />
              )}
            </main>
          </>
        ) : (
          <>
            <Header
              isAdmin={false}
              currentView={view}
              onViewChange={handleViewChange}
              onHandlerLogin={handleHandlerLogout}
            />
            <main className="app-main">
              {isAdminRoute || view === 'login' ? (
                <LoginForm onLogin={handleLogin} loading={authLoading} />
              ) : view === 'handler-login' ? (
                <HandlerLogin onLogin={handleHandlerLogin} />
              ) : view === 'handler-dashboard' && handlerUser ? (
                <HandlerDashboard handlerUser={handlerUser} onLogout={handleHandlerLogout} />
              ) : (
                <>
                  {view === 'rules' && <Rules />}
                  {view === 'public' && <Home users={users} loading={usersLoading} />}
                </>
              )}
            </main>
          </>
        )}
      </div>
    </ConfigProvider>
  );
}

export default App;
