import React, { useState, useEffect } from "react";
import { FaMedal } from "react-icons/fa";
import axios from "axios";
import Apis from "../../APIs";
import { useAuth } from "../Auth/AuthContext";
import { useNavigate } from "react-router-dom"; // To navigate to the dashboard

const Assessment = () => {
  const { user, setUser } = useAuth(); // Assuming setUser is available to update user data
  const navigate = useNavigate(); // To handle navigation
  const [questions, setQuestions] = useState([]);
  const [answers, setAnswers] = useState([]);
  const [score, setScore] = useState(0);
  const [result, setResult] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [assessmentRecordId, setAssessmentRecordId] = useState(null); // To store the assessment record ID
  const [redirectPage, setRedirectPage] = useState(null); // Store the page to redirect after clicking "Ok"

  const optionLabels = ["A", "B", "C", "D"];

  // Fetch questions from the API
  useEffect(() => {
    const fetchQuestions = async () => {
      try {
        const response = await axios.get(Apis.QUESTION_API);
        const fetchedQuestions = response.data;
        setQuestions(fetchedQuestions);
        setAnswers(fetchedQuestions.map(() => Array(4).fill(null)));
        setLoading(false);
      } catch (err) {
        console.error("Error fetching questions:", err);
        setError("Failed to load questions. Please try again later.");
        setLoading(false);
      }
    };

    fetchQuestions();
  }, []);

  const handleRatingSelect = (qIndex, oIndex, rating) => {
    const newAnswers = [...answers];
    newAnswers[qIndex][oIndex] = rating;
    setAnswers(newAnswers);
  };

  const handleSubmit = async () => {
    setResult(true);

    // Create the payload in the required JSON format for the POST request
    const formattedResponses = questions.map((question, qIndex) => ({
      questionId: question._id,
      ratings: answers[qIndex].map((rating) => ({ rating })),
    }));

    const userId = user._id;

    const payload = {
      userId: userId,
      responses: formattedResponses,
    };

    try {
      const response = await axios.post(Apis.ASSESSMENT_API, payload);
      console.log("Assessment submitted successfully:", response.data);
      setAssessmentRecordId(response.data._id); // Store the assessment record ID
      fetchAssessmentRecord(response.data._id); // Fetch the assessment record
    } catch (error) {
      console.error("Error submitting assessment:", error);
    }
  };

  const fetchAssessmentRecord = async (recordId) => {
    try {
      const response = await axios.get(
        `${Apis.ASSESSMENT_API}/getAssessmentRecord/${recordId}`
      );
      const optionStats = response.data.optionStats;
      determineRedirect(optionStats); // Call function to determine redirect
    } catch (error) {
      console.error("Error fetching assessment record:", error);
    }
  };

  const determineRedirect = (optionStats) => {
    const maxOption = Object.entries(optionStats).reduce(
      (acc, [key, value]) => {
        if (value[1] > acc.count) {
          return { key, count: value[1] }; // Find option with the highest count of "1"
        }
        return acc;
      },
      { key: null, count: 0 }
    );

    switch (maxOption.key) {
      case "option1":
        setRedirectPage("/PdfC"); // Set the redirect page
        break;
      case "option2":
        setRedirectPage("/PdfC");
        break;
      case "option3":
        setRedirectPage("/PdfC");
        break;
      case "option4":
        setRedirectPage("/PdfC");
        break;
      default:
        setRedirectPage("/dashboard"); // Default fallback
    }
  };

  const handleOkClick = async () => {
    // Fetch the updated user data
    const fetchUserData = async () => {
      try {
        const response = await axios.get(`${Apis.USER_API}/${user._id}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        const updatedUserData = response.data;
        setUser(updatedUserData); // Update the user data in the context
        console.log("User data refreshed:", updatedUserData);
      } catch (error) {
        console.error("Error refreshing user data:", error);
      }
    };

    await fetchUserData();
    // window.location.reload();

    navigate(redirectPage); // Navigate to the determined PDF page
  };

  if (loading) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">Loading questions...</div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">{error}</div>
      </section>
    );
  }

  return (
    <>
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center p-5">
        {result ? (
          <div className="min-h-[400px] w-80 md:w-[400px] rounded-lg bg-white p-5 flex items-center justify-center flex-col gap-5">
            <h2 className="text-3xl text-center">
              Thank you for giving the assessment
            </h2>
            <h2 className="text-3xl text-center">
              To See Your Result Click Ok
            </h2>
            <FaMedal className="text-4xl text-yellow-400" />
            {/* <h3 className="font-semibold text-4xl">{score}</h3> */}
            <button
              onClick={handleOkClick} // Handle Ok click and navigate
              className="h-10 w-full rounded-lg bg-green-500 text-white hover:bg-green-700"
            >
              Ok
            </button>
          </div>
        ) : (
          <div className="min-h-[400px] w-full max-w-screen-md rounded-lg bg-white p-5">
            <h2 className="font-bold text-xl mb-5">
              Know Your Competency (KYC) - Assessment on DGCS Leadership Style :
              -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              Please choose your rating based on your preference. Rank 1 - Most
              Agreed; 2 - Agreed; 3 - Lesser agreed; 4 - Least Agreed. -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              only one option should be given for each rank for each questions.
              For the question one - if you give rank 4 for 1st option, the same
              rank 4 cannot be given for the other 3 options. -{" "}
            </h2>
            
            {questions.map((q, qIndex) => (
              <div key={q._id} className="mb-6">
                <h3 className="font-semibold text-lg mb-3">
                  {qIndex + 1}. {q.mainQuestion}
                </h3>
                <div className="flex flex-col gap-3">
                  {q.options.map((option, oIndex) => (
                    <div
                      key={option._id}
                      className="flex items-center justify-between"
                    >
                      <span>{`(${optionLabels[oIndex]}) ${option.option}`}</span>
                      <div className="flex gap-7">
                        {[1, 2, 3, 4].map((rating) => (
                          <button
                            key={rating}
                            onClick={() =>
                              handleRatingSelect(qIndex, oIndex, rating)
                            }
                            className={`w-8 h-8 rounded-full border-2 flex items-center justify-center ${
                              answers[qIndex][oIndex] === rating
                                ? "bg-green-500 text-white"
                                : "border-gray-300"
                            }`}
                          >
                            {rating}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            <div className="mt-5 flex justify-end">
              <button
                onClick={handleSubmit}
                className="h-10 w-32 rounded-lg bg-green-500 text-white hover:bg-green-700"
              >
                Submit
              </button>
            </div>
          </div>
        )}
      </section>
    </>
  );
};

export default Assessment;