import React from "react";
import { Box, Typography, CircularProgress, Alert, Paper } from "@mui/material";
import { useNavigate, useSearchParams } from "react-router-dom";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
import { useSimulation } from "./hooks/useSimulation";
import { useTimer } from "./hooks/useTimer";
import { useEvaluation } from "./hooks/useEvaluation";
import ErrorDisplay from "../common/ErrorDisplay";

const BenchmarkEvaluation = ({ sessionId, isDefaultDocument, onComplete }) => {
  const [searchParams] = useSearchParams();
  const isDefault =
    isDefaultDocument ||
    ["the-bitter-lesson", "hurricane-faq", "pokemon-guide"].includes(sessionId);

  const navigate = useNavigate();

  // Use our custom hooks
  const { formatElapsedTime, stopTimer } = useTimer();
  const {
    startingMessageIndex,
    evaluationComplete: simulationComplete,
    currentMessage,
  } = useSimulation(() => {
    if (onComplete) {
      onComplete();
    }
  });
  const {
    error,
    evaluationComplete: realComplete,
    currentStep,
    evaluationStarted,
    startEvaluation,
    currentStepLabel,
    totalSteps,
  } = useEvaluation(sessionId, () => {
    if (onComplete) {
      onComplete();
    }
  });

  // Handle automatic redirection when evaluation is complete
  React.useEffect(() => {
    if (realComplete || simulationComplete) {
      navigate(`/evaluation-display?session=${sessionId}`);
    }
  }, [realComplete, simulationComplete, sessionId, navigate]);

  // Start evaluation if not default and not started
  React.useEffect(() => {
    if (!isDefault && !evaluationStarted) {
      startEvaluation();
    }
  }, [isDefault, evaluationStarted, startEvaluation]);

  // Stop timer when complete
  React.useEffect(() => {
    if (realComplete || simulationComplete) {
      stopTimer();
    }
  }, [realComplete, simulationComplete, stopTimer]);

  const isComplete = realComplete || simulationComplete;
  const currentStepInfo = isDefault
    ? `${currentMessage.message} (${currentMessage.step}/${currentMessage.totalSteps})`
    : `${currentStepLabel} (${currentStep + 1}/${totalSteps})`;

  return (
    <Paper
      elevation={3}
      sx={{
        p: 4,
        mt: 3,
        mb: 3,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        minHeight: 200,
        position: "relative",
      }}
    >
      {/* Temps estimé */}
      <Box
        sx={{
          position: "absolute",
          top: 12,
          right: 12,
          backgroundColor: "rgba(0, 0, 0, 0.04)",
          borderRadius: "4px",
          px: 1,
          py: 0.5,
          display: "inline-flex",
          alignItems: "center",
        }}
      >
        <Typography
          variant="caption"
          sx={{
            fontSize: "0.675rem",
            color: "text.secondary",
            fontWeight: 500,
          }}
        >
          Estimated time ~ 1m30s
        </Typography>
      </Box>

      {error ? (
        <ErrorDisplay error={error} />
      ) : (
        <>
          {isComplete ? (
            <Alert severity="success" sx={{ width: "100%", mb: 3 }}>
              Evaluation completed successfully!
            </Alert>
          ) : (
            <>
              <CircularProgress size={60} sx={{ mb: 2 }} />
              <Typography variant="h6" component="div" gutterBottom>
                Benchmark evaluation...
              </Typography>

              {/* Step progress indicator */}
              <Typography variant="body1" color="text.secondary">
                {currentStepInfo}
              </Typography>

              {/* Timer display */}
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  mt: 1,
                  color: "text.secondary",
                  opacity: 0.5,
                }}
              >
                <Typography variant="body2">{formatElapsedTime()}</Typography>
              </Box>
            </>
          )}
        </>
      )}
    </Paper>
  );
};

export default BenchmarkEvaluation;
