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

function BenchmarkDisplayPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const sessionId = searchParams.get("session");
  const [benchmarkQuestions, setBenchmarkQuestions] = useState([]);
  const [datasetUrl, setDatasetUrl] = useState(null);
  const [isValidSession, setIsValidSession] = useState(true);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    console.log("BenchmarkDisplayPage useEffect - sessionId:", sessionId);

    if (!sessionId) {
      console.log("Session ID manquante, redirection vers l'accueil");
      setIsValidSession(false);
      return;
    }

    setIsLoading(true);

    const fetchBenchmarkQuestions = async () => {
      console.log(
        "Tentative de récupération des questions pour la session:",
        sessionId
      );
      try {
        const apiUrl = `http://localhost:3001/benchmark-questions/${sessionId}`;
        console.log("Appel API:", apiUrl);

        const response = await fetch(apiUrl);
        console.log("Réponse API reçue:", response.status);

        if (!response.ok) {
          if (response.status === 404) {
            console.error("Session non trouvée");
            setIsValidSession(false);
            return;
          } else {
            console.error(`Erreur serveur: ${response.status}`);
            setIsLoading(false);
            return;
          }
        }

        const data = await response.json();
        console.log("Données API:", data);

        if (data.success && data.questions && data.questions.length > 0) {
          console.log("Questions chargées avec succès:", data.questions);
          setBenchmarkQuestions(data.questions);
        } else {
          console.warn(
            "Échec du chargement des questions, utilisation des valeurs par défaut"
          );
        }

        if (data.dataset_url) {
          setDatasetUrl(data.dataset_url);
        } else {
          const url = `https://huggingface.co/datasets/yourbench/yourbench_${sessionId}`;
          setDatasetUrl(url);
          console.log("URL du dataset générée:", url);
        }
      } catch (error) {
        console.error("Erreur lors de la récupération des questions:", error);
        setIsValidSession(false);
      } finally {
        setIsLoading(false);
      }
    };

    fetchBenchmarkQuestions();
  }, [sessionId]);

  const handleStartEvaluation = () => {
    console.log("Starting evaluation with session ID:", sessionId);
    navigate(`/benchmark-evaluation?session=${sessionId}`);
  };

  const defaultSampleQuestions = [
    {
      id: 1,
      question: "What are the key features discussed in the document?",
      answer:
        "The document discusses features such as scalability, integration capabilities, and security measures that are important for enterprise solutions.",
      type: "single_shot",
    },
    {
      id: 2,
      question:
        "How does the proposed solution address the challenges mentioned in section 2 in relation to the overall market trends?",
      answer:
        "The proposed solution addresses the challenges by incorporating AI-driven analytics that adapt to changing market conditions while maintaining compliance with industry regulations, thus providing a competitive edge in the evolving marketplace.",
      type: "multi_hop",
    },
  ];

  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 rgba(0, 0, 0, 0.12)",
            borderRadius: 2,
            p: 4,
            bgcolor: "white",
          }}
        >
          <BenchmarkDisplay
            onStartEvaluation={handleStartEvaluation}
            sessionId={sessionId}
            datasetUrl={datasetUrl}
            sampleQuestions={
              benchmarkQuestions.length > 0
                ? benchmarkQuestions
                : defaultSampleQuestions
            }
          />
        </Box>
      )}
    </>
  );
}

export default BenchmarkDisplayPage;
