import React from "react";
import { Redirect } from "react-router-dom";
import "./AttemptExam.css";
import { authenticationService } from "../../../../_services";
import { selectorService } from "../../../../services/selectorService";
import {
  Layout,
  Avatar,
  Button,
  List,
  Tabs,
  Card,
  Collapse,
  Statistic,
  Col,
  Row,
  Tag
} from "antd";
import { Link } from "react-router-dom";
import QuestionDetail from "./QuestionDetail";
import parse from "html-react-parser";

const { Content } = Layout;
const { Header } = Layout;
const { TabPane } = Tabs;
const { Panel } = Collapse;
const { Countdown } = Statistic;

class AttemptExam extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentUser: authenticationService.currentUserValue,
      exam_id: "props.location.state.examId",
      showQuestion: false,
      activeDetailQuestion: {},
      activeQuestionIndex: -1,
      pauseUpdate: false,
    };

    this.onGetExamAttempt = this.onGetExamAttempt.bind(this);
    this.callbackFunction = this.callbackFunction.bind(this);
    this.callbackFunctionNext = this.callbackFunctionNext.bind(this);
    this.sendHeartbeat = this.sendHeartbeat.bind(this);
    this.stopExamUpdate = this.stopExamUpdate.bind(this);
    this.onSubmitExam = this.onSubmitExam.bind(this);
    this.onPauseExam = this.onPauseExam.bind(this);
    this.getExamModelToUpdate = this.getExamModelToUpdate.bind(this);
  }

  componentDidMount() {
    this.onGetExamAttempt();
    this.sendHeartbeat();
  }

  getExamModelToUpdate() {
    let tempAllQuestions = this.state.allQuestions;
    let questionsArray = [];
    if (tempAllQuestions === undefined) return;
    tempAllQuestions.map((question, index) => {
      let quest = {};
      quest.question_id = question.id;
      quest.answer_duration = 0;
      quest.is_reviewed = question.isReviewMarked;
      quest.is_visited = question.isVisited;
      let options = question.options;
      let answers = [];
      for (let i = 0; i < options.length; i++) {
        if (options[i].isSelected) {
          let ans = {};
          ans.id = options[i].id;
          answers.push(ans);
        }
      }
      quest.answers = answers;
      if (quest.is_visited) questionsArray.push(quest);
    });

    return questionsArray;
  }

  onPauseExam() {
    this.stopExamUpdate();

    selectorService.pauseExam(this.state.attempt_id)
      .then((_data) => {
        console.log("Exam Paused");
        // ✅ Go back to the previous page after pausing the exam
        window.history.back();
      })
      .catch((error) => {
        console.error("Error pausing exam:", error);
      });
  }

  onSubmitExam() {
    let questionsArray = this.getExamModelToUpdate();
    this.stopExamUpdate();

    selectorService
      .endExam(this.state.attempt_id, questionsArray)
      .then((_data) => {
        console.log("Exam Ended");

        // ✅ Trigger redirect
        this.setState({ redirect: true });
      })
      .catch((error) => {
        console.error("Error ending exam:", error);
      });
  }

  stopExamUpdate() {
    clearInterval(this.interval);
  }

  componentWillUnmount() {
    this.stopExamUpdate();
  }

  sendHeartbeat() {
    this.interval = setInterval(() => {
      if (this.state.pauseUpdate) {
        this.stopExamUpdate();
      } else {
        selectorService
          .heartbeat(this.state.attempt_id)
          .then((data) => {
            const result = data.result;
            this.setState({
              time_left: result,
            });
          });
      }
    }, 60000);
  }

  showDetailQuestion(question) {
    question.isVisited = true;
    this.state.sections[question.sectionIndx].questions[question.secQIndex] =
      question;
    this.state.allQuestions[question.index - 1] = question;
    let tempSections = this.state.sections;
    let tempAllQuestions = this.state.allQuestions;
    this.setState({
      showQuestion: true,
      activeDetailQuestion: question,
      activeQuestionIndex: question.index - 1,
      sections: tempSections,
      allQuestions: tempAllQuestions,
    });
    this.forceUpdate();
  }

  onQuestionClick(index) {
    let q = this.state.allQuestions[index - 1];
    this.showDetailQuestion(q);
  }

  onTabPaneClick() {
    this.setState({
      showQuestion: false,
      activeDetailQuestion: {},
      activeQuestionIndex: -1,
    });
  }

  onGetExamAttempt() {
    var attemptId;
    selectorService
      .createExamAttempt(this.props.location.state.examId)
      .then((data) => {
        const result = data.result;
        attemptId = result.attempt_id;
        let index1 = 0;
        selectorService.getExamAttempt(attemptId).then((data) => {
          const result = data.result;
          let sections1 = [];
          let questionsArray = [];
          sections1 = result.sections.map((item, secIndex) => {
            let quest = [];
            quest = item.questions.map((question, index) => {
              index1 = index1 + 1;
              question.index = index1;
              question.sectionIndx = secIndex;
              question.secQIndex = index;
              questionsArray.push(question);
              return question;
            });
            item.questions = quest;
            return item;
          });
          this.setState({
            attempt_id: attemptId,
            exam_id: result.exam_id,
            exam_language: result.exam_language,
            exam_name: result.exam_name,
            sections: sections1,
            time_left: result.time_left,
            deadline: Date.now() + result.time_left * 1000,
            allQuestions: questionsArray,
          });
        });
      });
  }

  callbackFunction = (question) => {
    let q = question;
    let indx = q.index;
    let secQuesIndx = q.secQIndex;
    this.state.sections[q.sectionIndx].questions[secQuesIndx] = q;
    this.state.allQuestions[indx - 1] = q;
    let tempSections = this.state.sections;
    let tempAllQuestions = this.state.allQuestions;
    this.setState({
      showQuestion: true,
      sections: tempSections,
      allQuestions: tempAllQuestions,
    });
  };

  callbackFunctionNext = (childData) => {
    // ✅ Extract selected answer IDs (just numbers)
    const selectedAnswers = childData.options
      .filter(option => option.isSelected)
      .map(option => option.id); // <-- plain IDs, not objects

    // ✅ Build the JSON object like your Kotlin version
    const answerObject = {
      question_id: childData.id,
      answer_duration: childData.answer_duration || 10,
      is_reviewed: childData.isReviewMarked || false,
      is_visited: true,
      answers: selectedAnswers
    };

    // ✅ Send it (stringify the full object)
    selectorService.updateExamStatus(this.state.attempt_id, JSON.stringify(answerObject));

    // ✅ Load next question
    const q = childData;
    const indx = q.index;
    const nxtQuestion = this.state.allQuestions[indx];
    this.showDetailQuestion(nxtQuestion);
  };

  callbackFunctionUpdateAnswer = (question) => {
    console.log("Answer Updated", question);
  }

  render() {

    if (this.state.redirect) {
      return (
        <Redirect
          to={{
            pathname: "/report",
            state: { attempt_id: this.state.attempt_id },
          }}
        />
      );
    }

    let listItems = "";
    let accordions = "";
    let activeQuestion = "";
    let total_notVisited = 0;
    let total_notAnswered = 0;
    let total_Answered = 0;
    let total_AnsweredReviwed = 0;
    let total_Reviwed = 0;

    let questionStatusLabel = {
      QuesttionStatusNotAnswered: "Not Answered",
      QuesttionStatusAnswered: "Answered",
      QuesttionStatusReview: "To Review",
      QuesttionStatusAnsweredReview: "Answered and To Review",
    };

    if (this.state.sections !== undefined) {
      let tempSections = this.state.sections.map((item, index) => {
        let tempQuestions = item.questions.map((question) => {
          let isAnswered = false;
          let options = question.options;
          let answered = [];
          for (let i = 0; i < options.length; i++) {
            if (options[i].isSelected) {
              answered.push(options[i]);
            }
          }
          if (answered.length > 0) isAnswered = true;
          let classN = "QuesttionStatusNotVisited";
          if (question.isVisited) classN = "QuesttionStatusNotAnswered";
          if (isAnswered && !question.isReviewMarked)
            classN = "QuesttionStatusAnswered";
          if (question.isReviewMarked && isAnswered) {
            classN = "QuesttionStatusAnsweredReview";
          }
          if (question.isReviewMarked && !isAnswered) {
            classN = "QuesttionStatusReview";
          }
          question.classN = classN;
          question.statusLabel = questionStatusLabel[classN];
          if (classN === "QuesttionStatusReview") total_Reviwed += 1;
          if (classN === "QuesttionStatusAnsweredReview")
            total_AnsweredReviwed += 1;
          if (classN === "QuesttionStatusAnswered") total_Answered += 1;
          if (classN === "QuesttionStatusNotAnswered") total_notAnswered += 1;
          if (classN === "QuesttionStatusNotVisited") total_notVisited += 1;
          return question;
        });
        item.questions = tempQuestions;
        return item;
      });

      this.state.sections = tempSections;
      let index1 = 0;
      activeQuestion = (
        <Layout>
          <QuestionDetail
            totalQuestion={this.state.allQuestions.length}
            question={this.state.activeDetailQuestion}
            updateAnswerCallback={this.callbackFunctionUpdateAnswer}
            parentCallbackNext={this.callbackFunctionNext}
            parentCallback={this.callbackFunction}
          />
        </Layout>
      );

      listItems = this.state.sections.map((item, index) => (
        <TabPane tab={item.subject_name} key={index}>
          {this.state.showQuestion ? (
            activeQuestion
          ) : (
            <Row gutter={40} className="AttemptQuestionGrid" style={{ padding: "20px" }}>
              {item.questions.map((question, index) => {
                let title = (
                  <>
                    <Avatar className={question.classN}>{question.index}</Avatar>
                    <div className="Outerline">
                      <div
                        className={
                          "HeaderQuestionStatusLabel " +
                          question.classN +
                          "Title"
                        }
                      >
                        {question.statusLabel}
                      </div>
                    </div>
                  </>
                );

                return (
                  <Col key={question.id} className="question-col">
                    <Card
                      hoverable
                      className={`question-card ${question.classN}-card`}
                      onClick={() => this.showDetailQuestion(question)}
                    >
                      <div className="question-card-header">
                        <span className="question-title">{title}</span>
                        <Tag color="blue" className="question-type">
                          {question.type_text}
                        </Tag>
                      </div>

                      <div className="question-content">
                        <p>{parse(question.question_text)}</p>
                      </div>
                    </Card>
                  </Col>
                );

              })}
            </Row>
          )}
        </TabPane>
      ));

      accordions = this.state.sections.map((item, index) => (
        <Panel header={item.subject_name} key={index}>
          <Row gutter={20}>
            {item.questions.map((question) => (
              <Col key={question.id}>
                <Avatar
                  className={question.classN}
                  onClick={this.onQuestionClick.bind(this, question.index)}
                >
                  {question.index}
                </Avatar>
              </Col>
            ))}
          </Row>
        </Panel>
      ));
    }

    return (
      <>
        <Layout>
          <Layout>
            <Header className="exam-header">
              <div className="exam-header-left">
                <span className="exam-title">{this.state.exam_name}</span>
              </div>

              <div className="exam-header-center">
                <Countdown
                  title="Time Left"
                  value={this.state.deadline}
                  onFinish={this.onSubmitExam}
                  className="exam-countdown"
                />
              </div>

              <div className="exam-header-right">
                <Button onClick={this.onPauseExam}>Leave</Button>
                <Button type="primary" onClick={this.onSubmitExam}>
                  Submit
                </Button>
              </div>
            </Header>


            <Content
              className="site-layout-background"
              style={{ padding: 24, margin: 0 }}
            >
              <Layout className="MainExamLayout">
                <Layout className="create-exam-card">
                  <Tabs
                    defaultActiveKey="1"
                    size="large"
                    type="line"
                    animated
                    onTabClick={this.onTabPaneClick.bind(this)}
                    className="create-exam-tabs"
                  >
                    {listItems}
                  </Tabs>
                </Layout>

                <Layout className="exam-status-card">
                  <div className="exam-status-section">
                    <table className="exam-status-table">
                      <tbody>
                        <tr>
                          <td>
                            <div className="status-item">
                              <Avatar className="status-avatar not-visited">{total_notVisited}</Avatar>
                              <span className="status-label">Not Visited</span>
                            </div>
                          </td>
                          <td>
                            <div className="status-item">
                              <Avatar className="status-avatar not-answered">{total_notAnswered}</Avatar>
                              <span className="status-label">Not Answered</span>
                            </div>
                          </td>
                        </tr>

                        <tr>
                          <td>
                            <div className="status-item">
                              <Avatar className="status-avatar answered">{total_Answered}</Avatar>
                              <span className="status-label">Answered</span>
                            </div>
                          </td>
                          <td>
                            <div className="status-item">
                              <Avatar className="status-avatar to-review">{total_Reviwed}</Avatar>
                              <span className="status-label">To Review</span>
                            </div>
                          </td>
                        </tr>

                        <tr>
                          <td colSpan="2">
                            <div className="status-item">
                              <Avatar className="status-avatar answered-review">{total_AnsweredReviwed}</Avatar>
                              <span className="status-label">Answered & To Review</span>
                            </div>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  <div className="exam-accordion">
                    <Collapse accordion>{accordions}</Collapse>
                  </div>
                </Layout>

              </Layout>
            </Content>
          </Layout>
        </Layout>
      </>
    );
  }
}

export default AttemptExam;
