import React, { useState, useEffect, useRef } from "react";
import { Box, CircularProgress } from "@mui/material";
import { useNavigate, useSearchParams, Navigate } from "react-router-dom";
import Intro from "../components/Intro";
import Generator from "../components/Benchmark/Generator";

function BenchmarkGenerationPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get("session");
  const isDefault = searchParams.get("isDefault") === "true";
  const [isValidSession, setIsValidSession] = useState(true);
  const hasRedirectedRef = useRef(false);

  useEffect(() => {
    if (!sessionId) {
      setIsValidSession(false);
    }
  }, [sessionId]);

  const handleGenerationComplete = (result) => {
    console.log("Benchmark generation completed:", result);
    if (result && result.success && !hasRedirectedRef.current) {
      hasRedirectedRef.current = true; // Marquer que la redirection a été faite
      // Légère pause avant de naviguer pour éviter les problèmes de synchronisation
      setTimeout(() => {
        navigate(`/benchmark-display?session=${sessionId}`);
      }, 500);
    }
  };

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

  return (
    <>
      <Intro />
      <Generator
        sessionId={sessionId}
        isDefaultDocument={isDefault}
        onComplete={handleGenerationComplete}
      />
    </>
  );
}

export default BenchmarkGenerationPage;
