import React from 'react';
import Loading from '../ComponentUtils/LoadingAnimation/Loading';
import { useAdminSession } from '../../contexts/AdminSessionContext.jsx';
import InitialAdminSetupForm from './InitialAdminSetupForm.jsx';
import AdminLoginForm from './AdminLoginForm.jsx';
import ForcePasswordChangeForm from './ForcePasswordChangeForm.jsx';

const AdminSessionGate = ({ children }) => {
  const { loading, needsSetup, isAuthenticated, error, user } = useAdminSession();

  if (loading) {
    return (
      <div className="admin-auth-wrapper">
        <Loading />
      </div>
    );
  }

  if (error) {
    return (
      <div className="admin-auth-wrapper">
        <div className="admin-auth-error">
          <p>Fehler beim Laden des Authentifizierungsstatus.</p>
          <p>{error.message || 'Bitte später erneut versuchen.'}</p>
        </div>
      </div>
    );
  }

  if (needsSetup) {
    return (
      <div className="admin-auth-wrapper">
        <InitialAdminSetupForm />
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="admin-auth-wrapper">
        <AdminLoginForm />
      </div>
    );
  }

  if (user?.requiresPasswordChange) {
    return (
      <div className="admin-auth-wrapper">
        <ForcePasswordChangeForm />
      </div>
    );
  }

  return <>{children}</>;
};

export default AdminSessionGate;
