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,
  Typography
} 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 = question.answer_duration;
      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) {
    this.updateAnswersForQuestion(this.state.activeDetailQuestion);

    // Mark the question as visited
    question.isVisited = true;

    // Update the question in both section and allQuestions arrays
    this.state.sections[question.sectionIndx].questions[question.secQIndex] = question;
    this.state.allQuestions[question.index - 1] = question;
    question.answer_duration = Date.now();

    // Save the current section index for returning to the same tab
    this.setState({
      showQuestion: true,
      activeDetailQuestion: question,
      activeQuestionIndex: question.index - 1,
      sections: this.state.sections,
      allQuestions: this.state.allQuestions,
      lastActiveSection: question.sectionIndx // Save the section index
    });

    this.updateAnswersForQuestion(question);
  }

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

  onTabPaneClick() {
    // Only handle the back navigation if we're in question detail view
    if (this.state.showQuestion) {
      this.updateAnswersForQuestion(this.state.activeDetailQuestion);

      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,
    });
  };

  updateAnswersForQuestion = (question) => {
    // ✅ Check if question exists and has options
    if (
      !question ||
      typeof question !== "object" ||
      !question.options ||
      !Array.isArray(question.options)
    ) {
      console.warn("⚠️ Skipped updateAnswersForQuestion — invalid or missing question.");
      return;
    }

    const duration =
      question.answer_duration
        ? Math.floor((Date.now() - question.answer_duration) / 1000)
        : 0;

    // ✅ Extract selected answer IDs (just numbers)
    const selectedAnswers = question.options
      .filter(option => option.isSelected)
      .map(option => option.id);

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

    // ✅ Send it (stringify the full object)
    try {
      selectorService.updateExamStatus(
        this.state.attempt_id,
        JSON.stringify(answerObject)
      );
    } catch (error) {
      console.error("❌ Failed to update exam status:", error);
    }
  };

  callbackFunctionNext = (childData) => {
    // ✅ 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, examId: this.state.exam_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 = (
        <div style={{ padding: '24px 24px 0' }}>
          <QuestionDetail
            totalQuestion={this.state.allQuestions.length}
            question={this.state.activeDetailQuestion}
            updateAnswerCallback={this.callbackFunctionUpdateAnswer}
            parentCallbackNext={this.callbackFunctionNext}
            parentCallback={this.callbackFunction}
          />
        </div>
      );
      listItems = this.state.sections.map((item, index) => (
        <TabPane tab={item.subject_name} key={index}>
          {this.state.showQuestion ? (
            activeQuestion
          ) : (
            <List
              style={{ margin: '0 8px' }}
              grid={{
                gutter: [24, 24], // increased spacing between cards
                xs: 1,    // <576px screens show 1 card
                sm: 2,    // ≥576px screens show 2 cards
                md: 3,    // ≥768px screens show 3 cards
                lg: 3,    // ≥992px screens show 3 cards
                xl: 3,    // ≥1200px screens show 3 cards
                xxl: 3,   // ≥1600px screens show 3 cards
              }}
              dataSource={item.questions}
              pagination={false}
              renderItem={question => (
                <List.Item style={{ margin: '0 8px' }}>
                  <Card
                    hoverable
                    className={`question-card ${question.classN}-card`}
                    onClick={() => this.showDetailQuestion(question)}
                    style={{
                      height: '150px',
                      position: 'relative',
                      margin: '4px' // small margin for the card itself
                    }}
                  >
                    <div className="question-card-header" style={{
                      marginBottom: '12px',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}>
                      <Avatar
                        className={question.classN}
                        style={{
                          width: '28px',
                          height: '28px',
                          fontSize: '14px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        {question.index}
                      </Avatar>
                      <Tag color="blue" style={{ margin: 0, fontSize: '12px' }}>
                        {question.type_text}
                      </Tag>
                    </div>

                    <div className="question-content">
                      <Typography.Paragraph
                        ellipsis={{ rows: 1 }}
                        style={{ margin: 0, fontSize: '14px' }}
                      >
                        {parse(question.question_text)}
                      </Typography.Paragraph>
                    </div>

                    <div style={{
                      position: 'absolute',
                      bottom: '12px',
                      right: '12px',
                      left: '12px',
                      paddingTop: '8px',
                      borderTop: '1px solid #e0e0e0',
                      textAlign: 'right'
                    }}>
                      <Tag
                        style={{
                          margin: 0,
                          border: 'none',
                          padding: '2px 8px',
                          fontSize: '12px',
                          borderRadius: '4px',
                          backgroundColor: question.classN === 'QuesttionStatusNotVisited' ? '#bfbfbf' :
                            question.classN === 'QuesttionStatusNotAnswered' ? '#ff4d4f' :
                              question.classN === 'QuesttionStatusAnswered' ? '#52c41a' :
                                question.classN === 'QuesttionStatusReview' ? '#faad14' :
                                  question.classN === 'QuesttionStatusAnsweredReview' ? '#1890ff' : '#bfbfbf',
                          color: 'white'
                        }}
                      >
                        {question.statusLabel}
                      </Tag>
                    </div>
                  </Card>
                </List.Item>
              )}
            />
          )}
        </TabPane>
      ));

      accordions = this.state.sections.map((item, index) => (
        <Panel header={item.subject_name} key={index}>
          <Row gutter={[10, 10]}>
            {item.questions.map((question) => {
              let bgColor = "#bfbfbf"; // Default (Not Visited)

              // Match with your computed classN
              switch (question.classN) {
                case "QuesttionStatusNotVisited":
                  bgColor = "#bfbfbf"; // gray
                  break;
                case "QuesttionStatusNotAnswered":
                  bgColor = "#ff4d4f"; // red
                  break;
                case "QuesttionStatusAnswered":
                  bgColor = "#52c41a"; // green
                  break;
                case "QuesttionStatusReview":
                  bgColor = "#faad14"; // orange
                  break;
                case "QuesttionStatusAnsweredReview":
                  bgColor = "#1890ff"; // blue
                  break;
                default:
                  bgColor = "#bfbfbf";
              }

              return (
                <Col key={question.id}>
                  <Avatar
                    style={{
                      backgroundColor: bgColor,
                      color: "#fff",
                      fontWeight: "bold",
                      cursor: "pointer",
                      width: 38,
                      height: 38,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      border: "1px solid #e0e0e0",
                    }}
                    onClick={() => this.onQuestionClick(question.index)}
                  >
                    {question.index}
                  </Avatar>
                </Col>
              );
            })}
          </Row>
        </Panel>
      ));
    }

    return (
      <>
        <Layout style={{ background: '#fff' }}>
          <Layout style={{ background: '#fff' }}>
            <Header className="exam-header" style={{ background: '#fff', borderBottom: '1px solid #e0e0e0' }}>
              <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>

            <Layout style={{ background: '#fff' }}>
              <Layout.Sider
                width={300}
                style={{
                  background: '#fff',
                  height: 'calc(100vh - 64px)',
                  padding: '20px 24px', // ⬅ added top & bottom padding
                  borderRight: '1px solid #e0e0e0',
                  position: 'fixed',
                  left: 0,
                  overflowY: 'auto',
                  boxSizing: 'border-box'
                }}
              >
                {/* Exam Stats Section */}
                <div style={{ margin: '20px 0' }}>
                  <div style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}>
                    <Avatar className="status-avatar not-visited">{total_notVisited}</Avatar>
                    <span style={{ marginLeft: 10 }}>Not Visited</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}>
                    <Avatar className="status-avatar not-answered">{total_notAnswered}</Avatar>
                    <span style={{ marginLeft: 10 }}>Not Answered</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}>
                    <Avatar className="status-avatar answered">{total_Answered}</Avatar>
                    <span style={{ marginLeft: 10 }}>Answered</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}>
                    <Avatar className="status-avatar to-review">{total_Reviwed}</Avatar>
                    <span style={{ marginLeft: 10 }}>To Review</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', margin: '10px 0' }}>
                    <Avatar className="status-avatar answered-review">{total_AnsweredReviwed}</Avatar>
                    <span style={{ marginLeft: 10 }}>Answered & To Review</span>
                  </div>
                </div>

                {/* Accordion Section */}
                <div
                  className="exam-accordion"
                  style={{
                    background: '#fafafa',
                    borderRadius: '12px',
                    padding: '12px',
                    border: '1px solid #e0e0e0',
                    boxShadow: '0 2px 6px rgba(0,0,0,0.05)',
                  }}
                >
                  <Collapse
                    accordion
                    bordered={false}
                    expandIconPosition="end"
                    style={{
                      background: 'transparent',
                    }}
                    className="custom-accordion"
                  >
                    {accordions}
                  </Collapse>

                </div>
              </Layout.Sider>
              <Layout.Content style={{ marginLeft: '300px', padding: '0 24px', minHeight: 280, background: '#fff' }}>
                <Layout className="create-exam-card" style={{ background: '#fff' }}>
                  <Tabs
                    defaultActiveKey="1"
                    size="large"
                    type="line"
                    animated
                    onTabClick={this.onTabPaneClick.bind(this)}
                    className="create-exam-tabs"
                  >
                    {listItems}
                  </Tabs>
                </Layout>
              </Layout.Content>
            </Layout>
          </Layout>
        </Layout>
      </>
    );
  }
}

export default AttemptExam;
