import React, { useState, useEffect } from "react";
import { Box, CircularProgress } from "@mui/material";
import { useSearchParams, Navigate } from "react-router-dom";
import Intro from "../components/Intro";
import EvaluationDisplay from "../components/EvaluationDisplay";
import { useThemeMode } from "../hooks/useThemeMode";
import getTheme from "../config/theme";

function EvaluationDisplayPage() {
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get("session");
  const [isValidSession, setIsValidSession] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const { mode } = useThemeMode();
  const theme = getTheme(mode);

  useEffect(() => {
    if (!sessionId) {
      console.log(
        "Session ID manquante pour l'affichage des résultats, redirection vers l'accueil"
      );
      setIsValidSession(false);
      return;
    }

    const checkSession = async () => {
      try {
        const response = await fetch(
          `http://localhost:3001/benchmark-questions/${sessionId}`
        );

        if (!response.ok) {
          console.error(
            `Session invalide ou erreur serveur: ${response.status}`
          );
          setIsValidSession(false);
        }
      } catch (error) {
        console.error("Erreur lors de la vérification de la session:", error);
        setIsValidSession(false);
      } finally {
        setIsLoading(false);
      }
    };

    checkSession();
  }, [sessionId]);

  if (!isValidSession) {
    return <Navigate to="/" />;
  }

  return (
    <>
      <Intro />
      {isLoading ? (
        <Box
          sx={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            mt: 8,
            mb: 8,
          }}
        >
          <CircularProgress size={60} />
        </Box>
      ) : (
        <Box
          sx={{
            border: `1px solid ${theme.palette.divider}`,
            borderRadius: 2,
            p: 4,
            bgcolor: "background.paper",
          }}
        >
          <EvaluationDisplay sessionId={sessionId} />
        </Box>
      )}
    </>
  );
}

export default EvaluationDisplayPage;
