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";
import API_CONFIG from "../config/api";
import { useThemeMode } from "../hooks/useThemeMode";
import getTheme from "../config/theme";

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);
  const { mode } = useThemeMode();
  const theme = getTheme(mode);

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

    if (!sessionId) {
      console.log("Missing session ID, redirecting to home");
      setIsValidSession(false);
      return;
    }

    setIsLoading(true);

    const fetchBenchmarkQuestions = async () => {
      console.log("Attempting to fetch questions for session:", sessionId);
      try {
        const apiUrl = `${API_CONFIG.BASE_URL}/benchmark-questions/${sessionId}`;
        console.log("API call:", apiUrl);

        const response = await fetch(apiUrl);
        console.log("API response received:", response.status);

        if (!response.ok) {
          if (response.status === 404) {
            console.error("Session not found");
            setIsValidSession(false);
            return;
          } else {
            console.error(`Server error: ${response.status}`);
            setIsLoading(false);
            return;
          }
        }

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

        if (data.success && data.questions && data.questions.length > 0) {
          console.log("Questions loaded successfully:", data.questions);
          setBenchmarkQuestions(data.questions);
        } else {
          console.warn("Failed to load questions, using default values");
        }

        if (data.dataset_url) {
          setDatasetUrl(data.dataset_url);
        } else {
          const url = `https://huggingface.co/datasets/yourbench/yourbench_${sessionId}`;
          setDatasetUrl(url);
          console.log("Dataset URL generated:", url);
        }
      } catch (error) {
        console.error("Error retrieving questions:", error);
        setIsValidSession(false);
      } finally {
        setIsLoading(false);
      }
    };

    fetchBenchmarkQuestions();
  }, [sessionId]);

  const handleStartEvaluation = () => {
    console.log("Starting evaluation with session ID:", sessionId);
    const isDefault = [
      "the-bitter-lesson",
      "hurricane-faq",
      "pokemon-guide",
    ].includes(sessionId);
    navigate(
      `/benchmark-evaluation?session=${sessionId}&isDefault=${
        isDefault ? "true" : "false"
      }`
    );
  };

  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 ${theme.palette.divider}`,
            borderRadius: 2,
            p: 4,
            bgcolor: "background.paper",
          }}
        >
          <BenchmarkDisplay
            onStartEvaluation={handleStartEvaluation}
            sessionId={sessionId}
            datasetUrl={datasetUrl}
            sampleQuestions={
              benchmarkQuestions.length > 0
                ? benchmarkQuestions
                : defaultSampleQuestions
            }
          />
        </Box>
      )}
    </>
  );
}

export default BenchmarkDisplayPage;
