import React from "react";
import {
  Layout,
  List,
  Avatar,
  Button,
  Space,
  Divider,
  Tabs,
  Row,
  Col,
  Anchor,
  Menu,
  Drawer,
  Radio,
  Checkbox,
  Select,
  Empty,
} from "antd";
import "antd/dist/antd.css";
import {
  CheckCircleTwoTone,
  CloseCircleTwoTone,
  MinusCircleTwoTone,
  PlusCircleOutlined,
} from "@ant-design/icons";
import parse from "html-react-parser";
import { authenticationService } from "../../../../_services";
import { Siderc } from "../../../Main/Siderc";
import { Headerc } from "../../../Main/Headerc";
import { selectorService } from "../../../../services/selectorService";
// import { Link } from "react-router-dom";
import Plot from "react-plotly.js";
import { DashboardOutlined, PieChartOutlined } from "@ant-design/icons";
import "./Report.css";
import { useLocation } from "react-router-dom/cjs/react-router-dom.min";
const { Content } = Layout;
const { TabPane } = Tabs;

class Report extends React.Component {
  state = {
    currentUser: authenticationService.currentUserValue,
    classes: "1",
    batch: "1",
    data: [],
    total_count: 0,
    total_pages: 0,
    sections: [],
    view: {},
    visible: false,
    typeDropdown: [],
    typeDifficulty: [],
    attempt_id: this.props.location.state?.attempt_id || null,
  };

  componentDidMount() {
    this.handleLoadReportForExam();
  }

  handleCancel = (e) => {
    // console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleChange(value) {
    this.setState({ value });
  }

  handleLoadReportForExam() {
    selectorService
      .loadReport(this.state.attempt_id)
      .then((data) => {
        console.log(data);
        const result = data.result;
        let sections1 = [];
        let total_least_mark = 0;
        let total_max_mark = 0;
        let totalMarksReceived = 0;
        let totalMarks = 0;
        let total_correct_answer = 0;
        let total_wrong_answer = 0;
        let total_notAttempted_answer = 0;
        for (let index = 0; index < result.sections.length; index++) {
          let section = result.sections[index];
          let section_correct_answer = 0;
          let section_wrong_answer = 0;
          let section_notAttempted_answer = 0;
          let totalSectionMarks = 0;
          let easy_correct = 0;
          let easy_wrong_answer = 0;
          let easy_notAttempted_answer = 0;
          let medium_correct = 0;
          let medium_wrong_answer = 0;
          let medium_notAttempted_answer = 0;
          let hard_correct = 0;
          let hard_wrong_answer = 0;
          let hard_notAttempted_answer = 0;
          let total_MCQ = 0,
            total_MRQ = 0,
            total_TF = 0;
          let total_MCQ_correct = 0,
            total_MCQ_attempt = 0,
            total_MRQ_correct = 0,
            total_MRQ_attempt = 0,
            total_TF_correct = 0,
            total_TF_attempt = 0;
          totalMarks = totalMarks + result.sections[index].total_marks;
          if (total_max_mark < result.sections[index].total_marks) {
            total_max_mark = result.sections[index].total_marks;
          }
          if (total_least_mark > result.sections[index].total_nMarks) {
            total_least_mark = result.sections[index].total_nMarks;
          }

          let questions = result.sections[index].questions;
          for (let index1 = 0; index1 < questions.length; index1++) {
            if (questions[index1].isCorrect) {
              total_correct_answer++;
              section_correct_answer++;
              totalSectionMarks =
                totalSectionMarks + questions[index1].correct_marks;
              if (section.complexity_code === 1) easy_correct++;
              else if (section.complexity_code === 2) {
                medium_correct++;
              } else {
                hard_correct++;
              }
            } else if (questions[index1].isAttempted) {
              total_wrong_answer++;
              section_wrong_answer++;
              totalSectionMarks =
                totalSectionMarks - questions[index1].wrong_marks;
              if (section.complexity_code === 1) easy_wrong_answer++;
              else if (section.complexity_code === 2) {
                medium_wrong_answer++;
              } else {
                hard_wrong_answer++;
              }
            } else {
              total_notAttempted_answer++;
              section_notAttempted_answer++;
              if (section.complexity_code === 1) easy_notAttempted_answer++;
              else if (section.complexity_code === 2) {
                medium_notAttempted_answer++;
              } else {
                hard_notAttempted_answer++;
              }
            }
            if (questions[index1].type_code === "MCQ") {
              total_MCQ++;
              if (
                questions[index1].isAttempted &&
                questions[index1].isCorrect
              ) {
                total_MCQ_correct++;
                total_MCQ_attempt++;
              } else if (questions[index1].isAttempted) total_MCQ_attempt++;
            } else if (questions[index1].type_code === "MRQ") {
              total_MRQ++;
              if (
                questions[index1].isAttempted &&
                questions[index1].isCorrect
              ) {
                total_MRQ_correct++;
                total_MRQ_attempt++;
              } else if (questions[index1].isAttempted) total_MRQ_attempt++;
            } else {
              total_TF++;
              if (
                questions[index1].isAttempted &&
                questions[index1].isCorrect
              ) {
                total_TF_correct++;
                total_TF_attempt++;
              } else if (questions[index1].isAttempted) total_TF_attempt++;
            }
          }
          section.total_MCQ_attempt = total_MCQ_attempt;
          section.total_MRQ_attempt = total_MRQ_attempt;
          section.total_TF_attempt = total_TF_attempt;
          section.total_MCQ_correct = total_MCQ_correct;
          section.total_MRQ_correct = total_MRQ_correct;
          section.total_TF_correct = total_TF_correct;
          section.total_correct_answer = section_correct_answer;
          section.total_wrong_answer = section_wrong_answer;
          section.total_notAttempted_answer = section_notAttempted_answer;
          section.totalSectionMarks = totalSectionMarks;
          section.easy = {
            total: easy_correct + easy_notAttempted_answer + easy_wrong_answer,
            correct: easy_correct,
            wrong: easy_wrong_answer,
            notAttempted: easy_notAttempted_answer,
          };
          section.medium = {
            total:
              medium_correct + medium_notAttempted_answer + medium_wrong_answer,
            correct: medium_correct,
            wrong: medium_wrong_answer,
            notAttempted: medium_notAttempted_answer,
          };
          section.hard = {
            total: hard_notAttempted_answer + hard_wrong_answer + hard_correct,
            correct: hard_correct,
            wrong: hard_wrong_answer,
            notAttempted: hard_notAttempted_answer,
          };
          totalMarksReceived = totalMarksReceived + totalSectionMarks;
          section.total_MCQ = total_MCQ;
          section.total_MRQ = total_MRQ;
          section.total_TF = total_TF;
          sections1.push(section);
        }
        this.setState({
          examName: result.exam_name,
          sections: sections1,
          totalMarksReceived: totalMarksReceived,
          totalMarks: totalMarks,
          total_least_mark: total_least_mark,
          total_max_mark: total_max_mark,
          total_correct_answer: total_correct_answer,
          total_wrong_answer: total_wrong_answer,
          total_notAttempted_answer: total_notAttempted_answer,
        });
        console.log(data);
      });
  }
  render() {
    const { Link } = Anchor;
    const { Option } = Select;
    let answerKey = [];
    let secNames = [];
    let secMarks = [];
    this.state.sections.map((item, secIndex) => {
      secNames.push(item.subject_name);
      secMarks.push(item.totalSectionMarks);
    });
    let percentage = 0;
    if (this.state.total_correct_answer !== 0) {
      percentage =
        (this.state.total_correct_answer * 100) /
        (this.state.total_correct_answer +
          this.state.total_wrong_answer +
          this.state.total_notAttempted_answer);
    }

    const tabs = (
      <Tabs defaultActiveKey="1">
        {this.state.sections.map((item, secIndex) => {
          console.log(item);
          return (
            <TabPane
              tab={
                <div
                  className="ReportTabHeader"
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    padding: "10px 16px",
                    borderRadius: "8px",
                    backgroundColor: "#f9f9f9",
                    transition: "all 0.25s ease",
                    fontFamily: "Inter, sans-serif",
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = "#e6f4ff";
                    e.currentTarget.style.boxShadow = "0 2px 6px rgba(0,0,0,0.1)";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = "#f9f9f9";
                    e.currentTarget.style.boxShadow = "none";
                  }}
                >
                  <div
                    style={{
                      fontSize: "16px",
                      fontWeight: 600,
                      color: "#1a1a1a",
                      textAlign: "center",
                      whiteSpace: "nowrap",
                    }}
                  >
                    {item.subject_name}
                  </div>
                  <div
                    style={{
                      fontSize: "14px",
                      fontWeight: 500,
                      color: "#1677ff",
                      marginTop: "2px",
                    }}
                  >
                    {item.totalSectionMarks}/{item.total_marks}
                  </div>
                </div>
              }
              key={secIndex}
            >

              <Row>

                <Col span={20} offset={1}>
                  <div style={{ width: "100%", marginTop: "32px" }}>
                    <h3
                      id="components-anchor-overall"
                      className="SectionHeaderReport"
                      style={{
                        fontSize: "20px",
                        fontWeight: 600,
                        color: "#1a1a1a",
                        marginBottom: "8px",
                      }}
                    >
                      Overall
                    </h3>

                    <p style={{ color: "#555", fontSize: "15px", marginBottom: "24px" }}>
                      A quick summary of your total <b>Score</b> and <b>Accuracy</b> across this section.
                    </p>

                    {/* ✅ Grey background for the section */}
                    <div
                      style={{
                        backgroundColor: "#F5F7FA",
                        borderRadius: "16px",
                        padding: "32px 24px",
                        boxShadow: "inset 0 0 6px rgba(0,0,0,0.05)",
                      }}
                    >
                      <Row gutter={[24, 24]} justify="center" align="stretch">
                        {/* SCORE CARD */}
                        <Col xs={24} sm={12} md={10}>
                          <div
                            style={{
                              background: "#fff",
                              borderRadius: "12px",
                              padding: "24px",
                              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                              transition: "transform 0.2s ease",
                              overflow: "hidden",
                              borderTop: "4px solid #1677ff",
                              display: "flex",
                              flexDirection: "column",
                              justifyContent: "space-between",
                              height: "100%",          // ✅ makes it stretch equal
                              minHeight: "400px",      // ✅ consistent visual height
                            }}
                            onMouseEnter={(e) =>
                              (e.currentTarget.style.transform = "translateY(-4px)")
                            }
                            onMouseLeave={(e) =>
                              (e.currentTarget.style.transform = "translateY(0)")
                            }
                          >
                            <div>
                              <div
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  justifyContent: "space-between",
                                  marginBottom: "16px",
                                }}
                              >
                                <h3
                                  style={{
                                    fontSize: "18px",
                                    fontWeight: 600,
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "8px",
                                  }}
                                >
                                  <DashboardOutlined style={{ color: "#1677ff" }} />
                                  Score
                                </h3>
                                <span
                                  style={{
                                    fontSize: "20px",
                                    fontWeight: 700,
                                    color: "#1a1a1a",
                                  }}
                                >
                                  {item.totalSectionMarks}/{item.total_marks}
                                </span>
                              </div>

                              <div
                                style={{
                                  textAlign: "center",
                                  padding: "12px 0",
                                  fontSize: "15px",
                                  color: "#555",
                                }}
                              >
                                You scored{" "}
                                <b style={{ color: "#1677ff" }}>{item.totalSectionMarks}</b> out of{" "}
                                <b>{item.total_marks}</b> total marks.
                              </div>
                            </div>

                            {/* Optional: You can add a small mini bar chart or graphic here to match height */}
                            <div
                              style={{
                                flexGrow: 1,
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                              }}
                            >
                              <Plot
                                data={[
                                  {
                                    type: "bar",
                                    x: ["Your Score"],
                                    y: [item.totalSectionMarks],
                                    marker: { color: "#1677ff" },
                                  },
                                ]}
                                layout={{
                                  height: 200,
                                  margin: { t: 10, b: 40, l: 40, r: 10 },
                                  yaxis: { range: [0, item.total_marks], showgrid: false },
                                  xaxis: { tickfont: { size: 12 } },
                                  showlegend: false,
                                  paper_bgcolor: "rgba(0,0,0,0)",
                                  plot_bgcolor: "rgba(0,0,0,0)",
                                }}
                                config={{ displayModeBar: false, responsive: true }}
                                style={{ width: "100%" }}
                              />
                            </div>
                          </div>
                        </Col>

                        {/* ACCURACY CARD */}
                        <Col xs={24} sm={12} md={10}>
                          <div
                            style={{
                              background: "#fff",
                              borderRadius: "12px",
                              padding: "24px",
                              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                              transition: "transform 0.2s ease",
                              overflow: "hidden",
                              borderTop: "4px solid #52c41a",
                              display: "flex",
                              flexDirection: "column",
                              justifyContent: "space-between",
                              height: "100%",          // ✅ same height as Score
                              minHeight: "400px",
                            }}
                            onMouseEnter={(e) =>
                              (e.currentTarget.style.transform = "translateY(-4px)")
                            }
                            onMouseLeave={(e) =>
                              (e.currentTarget.style.transform = "translateY(0)")
                            }
                          >
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "space-between",
                                marginBottom: "16px",
                              }}
                            >
                              <h3
                                style={{
                                  fontSize: "18px",
                                  fontWeight: 600,
                                  display: "flex",
                                  alignItems: "center",
                                  gap: "8px",
                                }}
                              >
                                <PieChartOutlined style={{ color: "#52c41a" }} />
                                Accuracy
                              </h3>
                              <span
                                style={{
                                  fontSize: "20px",
                                  fontWeight: 700,
                                  color: "#52c41a",
                                }}
                              >
                                {(
                                  (item.total_correct_answer * 100) /
                                  (item.total_correct_answer +
                                    item.total_wrong_answer +
                                    item.total_notAttempted_answer)
                                ).toFixed(1)}
                                %
                              </span>
                            </div>

                            <div style={{ display: "flex", justifyContent: "center" }}>
                              <Plot
                                data={[
                                  {
                                    type: "pie",
                                    values: [
                                      item.total_correct_answer,
                                      item.total_wrong_answer,
                                      item.total_notAttempted_answer,
                                    ],
                                    labels: ["Correct", "Incorrect", "Not Attempted"],
                                    marker: {
                                      colors: ["#52c41a", "#ff4d4f", "#d9d9d9"],
                                    },
                                    textinfo: "label+percent",
                                    hoverinfo: "label+value",
                                    hole: 0.4,
                                  },
                                ]}
                                layout={{
                                  height: 250,
                                  width: 350,
                                  margin: { t: 60, b: 60, l: 60, r: 60 },
                                  showlegend: true,
                                  legend: {
                                    orientation: "h",
                                    y: -0.3,
                                    font: { size: 12 },
                                  },
                                  paper_bgcolor: "rgba(0,0,0,0)",
                                  plot_bgcolor: "rgba(0,0,0,0)",
                                }}
                                config={{ displayModeBar: false, responsive: true }}
                              />
                            </div>
                          </div>
                        </Col>
                      </Row>
                    </div>

                  </div>

                  <div style={{ width: "100%", marginTop: "48px" }}>
                    <h3
                      id="components-anchor-difficulty"
                      className="SectionHeaderReport"
                      style={{
                        fontSize: "20px",
                        fontWeight: 600,
                        color: "#1a1a1a",
                        marginBottom: "8px",
                      }}
                    >
                      Difficulty Levels
                    </h3>

                    <p style={{ color: "#555", fontSize: "15px" }}>
                      Performance across questions of different difficulty levels —{" "}
                      <b>Easy</b>, <b>Medium</b> & <b>Hard</b>.
                    </p>

                    {/* Grey background wrapper */}
                    <div
                      style={{
                        width: "100%",
                        backgroundColor: "#F5F7FA",
                        borderRadius: "16px",
                        padding: "32px 24px",
                        marginTop: "24px",
                      }}
                    >
                      <Row gutter={[24, 24]} justify="center">
                        {[
                          {
                            label: "Easy",
                            color: "#52c41a",
                            data: item.easy,
                          },
                          {
                            label: "Medium",
                            color: "#1677ff",
                            data: item.medium,
                          },
                          {
                            label: "Hard",
                            color: "#ff4d4f",
                            data: item.hard,
                          },
                        ].map((d, i) => (
                          <Col xs={24} sm={12} md={8} key={i}>
                            <div
                              style={{
                                background: "#fff",
                                borderRadius: "12px",
                                padding: "20px",
                                boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                                transition: "transform 0.2s ease",
                                overflow: "hidden",
                                borderTop: `4px solid ${d.color}`, // Color accent
                              }}
                              onMouseEnter={(e) =>
                                (e.currentTarget.style.transform = "translateY(-4px)")
                              }
                              onMouseLeave={(e) =>
                                (e.currentTarget.style.transform = "translateY(0)")
                              }
                            >
                              {/* Header */}
                              <div
                                style={{
                                  display: "flex",
                                  justifyContent: "space-between",
                                  alignItems: "center",
                                  marginBottom: "12px",
                                }}
                              >
                                <h3
                                  style={{
                                    margin: 0,
                                    fontSize: "18px",
                                    fontWeight: 600,
                                    color: d.color,
                                  }}
                                >
                                  {d.label}
                                </h3>
                                <span style={{ color: "#888", fontSize: "14px" }}>
                                  {d.data.total} Questions
                                </span>
                              </div>

                              {/* Accuracy */}
                              <div
                                style={{
                                  display: "flex",
                                  justifyContent: "space-between",
                                  alignItems: "center",
                                  marginBottom: "8px",
                                }}
                              >
                                <span style={{ fontWeight: 600, color: "#444" }}>Accuracy</span>
                                <span style={{ fontSize: "16px", color: d.color }}>
                                  {d.data.total > 0
                                    ? ((d.data.correct * 100) / d.data.total).toFixed(1)
                                    : 0}
                                  %
                                </span>
                              </div>

                              {/* Chart */}
                              <Plot
                                data={[
                                  {
                                    type: "bar",
                                    x: ["Correct", "Incorrect", "Not Ans"],
                                    y: [d.data.correct, d.data.wrong, d.data.notAttempted],
                                    marker: { color: ["#52c41a", "#ff4d4f", "#d9d9d9"] },
                                    width: 0.5,
                                  },
                                ]}
                                layout={{
                                  autosize: true,
                                  height: 230,
                                  margin: { l: 40, r: 10, t: 10, b: 40 },
                                  xaxis: {
                                    tickfont: { size: 12 },
                                    showgrid: false,
                                    zeroline: false,
                                    showline: false,
                                  },
                                  yaxis: {
                                    range: [0, Math.max(1, d.data.total)],
                                    showgrid: false,
                                    zeroline: false,
                                    showline: false,
                                  },
                                  paper_bgcolor: "rgba(0,0,0,0)",
                                  plot_bgcolor: "rgba(0,0,0,0)",
                                  showlegend: false,
                                  bargap: 0.3,
                                  bargroupgap: 0.2,
                                }}
                                config={{ displayModeBar: false, responsive: true }}
                                style={{ width: "100%" }}
                              />
                            </div>
                          </Col>
                        ))}
                      </Row>
                    </div>
                  </div>

                  <br />
                  <div style={{ width: "100%", marginTop: "48px" }}>
                    <h3
                      id="components-anchor-type"
                      className="SectionHeaderReport"
                      style={{
                        fontSize: "20px",
                        fontWeight: 600,
                        color: "#1a1a1a",
                        marginBottom: "8px",
                      }}
                    >
                      Question Type
                    </h3>

                    <p style={{ color: "#555", fontSize: "15px" }}>
                      Performance across question types — <b>MCQ</b>, <b>MRQ</b>, and{" "}
                      <b>True & False</b>.
                    </p>

                    {/* ✅ Grey section background */}
                    <div
                      style={{
                        width: "100%",
                        backgroundColor: "#F5F7FA",
                        borderRadius: "16px",
                        padding: "32px 24px",
                        marginTop: "24px",
                      }}
                    >
                      <Row gutter={[24, 24]} justify="center">
                        {[
                          {
                            title: "MCQ",
                            total: item.total_MCQ,
                            correct: item.total_MCQ_correct,
                            attempt: item.total_MCQ_attempt,
                            totalQ: item.total_MCQ,
                          },
                          {
                            title: "MRQ",
                            total: item.total_MRQ,
                            correct: item.total_MRQ_correct,
                            attempt: item.total_MRQ_attempt,
                            totalQ: item.total_MRQ,
                          },
                          {
                            title: "True / False",
                            total: item.total_TF,
                            correct: item.total_TF_correct,
                            attempt: item.total_TF_attempt,
                            totalQ: item.total_TF,
                          },
                        ].map((t, i) => (
                          <Col xs={24} sm={12} md={8} key={i}>
                            <div
                              style={{
                                background: "#fff",
                                borderRadius: "12px",
                                padding: "20px",
                                boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                                transition: "transform 0.2s ease",
                                overflow: "hidden", // ✅ prevents chart overflow
                              }}
                              onMouseEnter={(e) =>
                                (e.currentTarget.style.transform = "translateY(-4px)")
                              }
                              onMouseLeave={(e) =>
                                (e.currentTarget.style.transform = "translateY(0)")
                              }
                            >
                              {/* Header */}
                              <div
                                style={{
                                  display: "flex",
                                  justifyContent: "space-between",
                                  alignItems: "center",
                                  marginBottom: "12px",
                                }}
                              >
                                <h3
                                  style={{
                                    margin: 0,
                                    fontSize: "18px",
                                    fontWeight: 600,
                                    color: "#1a1a1a",
                                  }}
                                >
                                  {t.title}
                                </h3>
                                <span style={{ color: "#888", fontSize: "14px" }}>
                                  {t.total} Questions
                                </span>
                              </div>

                              {/* Accuracy */}
                              <div
                                style={{
                                  display: "flex",
                                  justifyContent: "space-between",
                                  alignItems: "center",
                                  marginBottom: "8px",
                                }}
                              >
                                <span style={{ fontWeight: 600, color: "#444" }}>Accuracy</span>
                                <span style={{ fontSize: "16px", color: "#1677ff" }}>
                                  {isNaN((t.correct / t.attempt) * 100)
                                    ? 0
                                    : ((t.correct / t.attempt) * 100).toFixed(1)}
                                  %
                                </span>
                              </div>

                              {/* Plotly Chart */}
                              <Plot
                                data={[
                                  {
                                    type: "bar",
                                    x: ["Correct", "Incorrect", "Not Ans"],
                                    y: [
                                      t.correct,
                                      t.attempt - t.correct,
                                      t.totalQ - t.attempt,
                                    ],
                                    marker: { color: ["#52c41a", "#ff4d4f", "#d9d9d9"] },
                                    width: 0.5,
                                  },
                                ]}
                                layout={{
                                  autosize: true,
                                  height: 230,
                                  margin: { l: 40, r: 10, t: 10, b: 40 },
                                  xaxis: {
                                    tickfont: { size: 12 },
                                    showgrid: false,
                                    zeroline: false,
                                    showline: false,
                                  },
                                  yaxis: {
                                    range: [
                                      0,
                                      Math.max(
                                        1,
                                        t.correct,
                                        t.attempt - t.correct,
                                        t.totalQ - t.attempt
                                      ),
                                    ],
                                    showgrid: false,
                                    zeroline: false,
                                    showline: false,
                                  },
                                  paper_bgcolor: "rgba(0,0,0,0)",
                                  plot_bgcolor: "rgba(0,0,0,0)",
                                  showlegend: false,
                                  bargap: 0.3,
                                  bargroupgap: 0.2,
                                }}
                                config={{ displayModeBar: false, responsive: true }}
                                style={{ width: "100%" }}
                              />
                            </div>
                          </Col>
                        ))}
                      </Row>
                    </div>
                  </div>

                  <br />
                  {/* ANSWER KEY */}
                  <div style={{ width: "100%", marginTop: "48px" }}>
                    <h3
                      id="components-anchor-answer"
                      style={{
                        fontSize: "20px",
                        fontWeight: 600,
                        marginBottom: "8px",
                        color: "#1a1a1a",
                      }}
                    >
                      Answer Key
                    </h3>

                    {/* Stats Row */}
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        flexWrap: "wrap",
                        marginBottom: "16px",
                      }}
                    >
                      {/* Stats */}
                      <div style={{ display: "flex", gap: "16px", flexWrap: "wrap" }}>
                        <div
                          style={{
                            background: "#fff",
                            borderRadius: "10px",
                            padding: "10px 16px",
                            boxShadow: "0 2px 6px rgba(0,0,0,0.08)",
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                            fontWeight: 500,
                          }}
                        >
                          <CheckCircleTwoTone twoToneColor="#52c41a" />
                          <span>
                            Correct: <strong>{item.total_correct_answer}</strong>
                          </span>
                        </div>

                        <div
                          style={{
                            background: "#fff",
                            borderRadius: "10px",
                            padding: "10px 16px",
                            boxShadow: "0 2px 6px rgba(0,0,0,0.08)",
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                            fontWeight: 500,
                          }}
                        >
                          <CloseCircleTwoTone twoToneColor="red" />
                          <span>
                            Incorrect: <strong>{item.total_wrong_answer}</strong>
                          </span>
                        </div>

                        <div
                          style={{
                            background: "#fff",
                            borderRadius: "10px",
                            padding: "10px 16px",
                            boxShadow: "0 2px 6px rgba(0,0,0,0.08)",
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                            fontWeight: 500,
                          }}
                        >
                          <MinusCircleTwoTone twoToneColor="grey" />
                          <span>
                            Not Attempted: <strong>{item.total_notAttempted_answer}</strong>
                          </span>
                        </div>
                      </div>

                      {/* Filters */}
                      <div
                        style={{
                          display: "flex",
                          gap: "16px",
                          flexWrap: "wrap",
                          justifyContent: "flex-end",
                        }}
                      >
                        <Select
                          maxTagCount={1}
                          mode="tags"
                          showArrow
                          style={{ width: 180 }}
                          placeholder="Question Type"
                          onChange={(value) => {
                            this.setState({ typeDropdown: value });
                          }}
                        >
                          <Option key="MCQ">MCQ</Option>
                          <Option key="MRQ">MRQ</Option>
                          <Option key="T&F">T&F</Option>
                        </Select>

                        <Select
                          maxTagCount={1}
                          mode="tags"
                          showArrow
                          style={{ width: 180 }}
                          placeholder="Difficulty Level"
                          onChange={(value) => {
                            let typeDifficulty = value.map((x) => parseInt(x));
                            this.setState({ typeDifficulty });
                          }}
                        >
                          <Option key="1">Easy</Option>
                          <Option key="2">Medium</Option>
                          <Option key="3">Hard</Option>
                        </Select>
                      </div>
                    </div>

                    {/* Questions Grid */}
                    <div
                      style={{
                        width: "100%",
                        backgroundColor: "#F5F7FA",
                        borderRadius: "16px",
                        padding: "24px",
                        boxShadow: "inset 0 0 8px rgba(0,0,0,0.05)",
                      }}
                    >
                      <Row gutter={[16, 16]}>
                        <Col span={18}>
                          <Row gutter={[16, 16]}>
                            {(() => {
                              const filtered = item.questions
                                .filter((q) => {
                                  const { typeDropdown, typeDifficulty } = this.state;
                                  const matchType =
                                    !typeDropdown?.length ||
                                    typeDropdown.includes(q.type_code);
                                  const matchDiff =
                                    !typeDifficulty?.length ||
                                    typeDifficulty.includes(q.complexity_code);
                                  return matchType && matchDiff;
                                })
                                .map((q, index) => (
                                  <Col xs={24} sm={12} md={8} key={index}>
                                    <div
                                      onClick={() =>
                                        this.setState({ view: { ...q, index }, visible: true })
                                      }
                                      style={{
                                        background: "#fff",
                                        borderRadius: "12px",
                                        padding: "16px",
                                        minHeight: "240px",
                                        boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                                        border: `2px solid ${q.isCorrect
                                          ? "#52c41a"
                                          : q.isAttempted
                                            ? "#ff4d4f"
                                            : "#d9d9d9"
                                          }`,
                                        cursor: "pointer",
                                        position: "relative",
                                        transition: "all 0.2s ease-in-out",
                                      }}
                                      onMouseEnter={(e) =>
                                        (e.currentTarget.style.transform = "translateY(-4px)")
                                      }
                                      onMouseLeave={(e) =>
                                        (e.currentTarget.style.transform = "translateY(0)")
                                      }
                                    >
                                      <div
                                        style={{
                                          display: "flex",
                                          justifyContent: "space-between",
                                          marginBottom: "8px",
                                        }}
                                      >
                                        <strong style={{ fontSize: "18px" }}>
                                          Q{index + 1}
                                        </strong>
                                        <span
                                          style={{
                                            color: q.isCorrect
                                              ? "#52c41a"
                                              : q.isAttempted
                                                ? "#ff4d4f"
                                                : "grey",
                                            fontWeight: 500,
                                          }}
                                        >
                                          {q.isCorrect
                                            ? "Correct"
                                            : q.isAttempted
                                              ? "Incorrect"
                                              : "Unanswered"}
                                        </span>
                                      </div>
                                      <div
                                        style={{
                                          fontSize: "15px",
                                          color: "#333",
                                          overflow: "hidden",
                                          display: "-webkit-box",
                                          WebkitLineClamp: 3, // 👈 number of visible lines before truncation
                                          WebkitBoxOrient: "vertical",
                                          textOverflow: "ellipsis",
                                          whiteSpace: "normal",
                                          minHeight: "60px",
                                        }}
                                        title={q.question_text.replace(/(<([^>]+)>)/gi, "")} // optional tooltip for full text
                                      >
                                        {parse(q.question_text)}
                                      </div>

                                      <div
                                        style={{
                                          position: "absolute",
                                          right: "12px",
                                          bottom: "12px",
                                          fontSize: "13px",
                                          backgroundColor: "#f0f2f5",
                                          padding: "4px 8px",
                                          borderRadius: "6px",
                                          color: "#555",
                                          display: "flex",
                                          alignItems: "center",
                                          gap: "6px",
                                        }}
                                      >
                                        <PlusCircleOutlined /> {q.type_code}
                                      </div>
                                    </div>
                                  </Col>
                                ));

                              return filtered.length ? (
                                filtered
                              ) : (
                                <div style={{ width: "100%", textAlign: "center", marginTop: 32 }}>
                                  <Empty description="No questions match selected filters" />
                                </div>
                              );
                            })()}
                          </Row>
                        </Col>

                        {/* Right Sidebar */}
                        <Col span={6}>
                          <div
                            style={{
                              background: "#fff",
                              padding: "16px",
                              borderRadius: "12px",
                              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                              height: "100%",
                            }}
                          >
                            <h4 style={{ fontWeight: 600, marginBottom: "12px" }}>
                              All Questions
                            </h4>
                            <div style={{ display: "flex", flexWrap: "wrap" }}>
                              {item.questions.map((q, index) => (
                                <Avatar
                                  key={index}
                                  onClick={() =>
                                    this.setState({ visible: true, view: { ...q, index } })
                                  }
                                  style={{
                                    margin: "6px",
                                    backgroundColor: q.isCorrect
                                      ? "#52c41a"
                                      : q.isAttempted
                                        ? "#ff4d4f"
                                        : "#d9d9d9",
                                    cursor: "pointer",
                                  }}
                                >
                                  {index + 1}
                                </Avatar>
                              ))}
                            </div>
                          </div>
                        </Col>
                      </Row>

                      {/* Drawer for Detailed Question View */}
                      <Drawer
                        title={
                          <div style={{ fontWeight: 600 }}>
                            Question #{this.state.view.index + 1}
                          </div>
                        }
                        width={640}
                        placement="right"
                        onClose={this.handleCancel}
                        visible={this.state.visible}
                        bodyStyle={{
                          backgroundColor: "#f9fafb",
                          paddingBottom: "40px",
                        }}
                      >
                        <Space direction="vertical" size="middle" style={{ width: "100%" }}>
                          <div
                            style={{
                              background: "#fff",
                              padding: "16px",
                              borderRadius: "12px",
                              boxShadow: "0 2px 8px rgba(0,0,0,0.06)",
                            }}
                          >
                            <h3 style={{ fontWeight: 500, fontSize: "16px", color: "#1a1a1a" }}>
                              {parse(this.state.view.question_text || "")}
                            </h3>
                          </div>

                          {/* Options */}
                          {this.state.view.type_code === "MRQ" ? (
                            <Checkbox.Group
                              options={this.state.view.options?.map((opt, i) => ({
                                label: opt.text,
                                value: i,
                                disabled: true,
                              }))}
                              disabled
                              defaultValue={[1]}
                            />
                          ) : this.state.view.type_code === "MCQ" || this.state.view.type_code === "TNF" ? (
                            <Radio.Group
                              disabled
                              value={
                                this.state.view.options?.find((x) => x.isCorrect)?.text || undefined
                              }
                            >
                              {this.state.view.options?.map((opt, idx) => (
                                <Radio key={idx} value={opt.text}>
                                  <span
                                    style={{
                                      color: opt.isCorrect
                                        ? "#52c41a"
                                        : opt.isAttempted
                                          ? "#ff4d4f"
                                          : "#888",
                                    }}
                                  >
                                    {opt.text}
                                  </span>
                                </Radio>
                              ))}
                            </Radio.Group>
                          ) : null}

                          {/* Difficulty Tag */}
                          <div>
                            <h4 style={{ marginBottom: 8 }}>Complexity</h4>
                            <Avatar
                              shape="square"
                              size="large"
                              style={{
                                backgroundColor:
                                  this.state.view.complexity_code === 1
                                    ? "#55B2FF"
                                    : this.state.view.complexity_code === 2
                                      ? "#52C41A"
                                      : "#F8515B",
                                width: 120,
                                fontWeight: 500,
                              }}
                            >
                              {this.state.view.complexity_code === 1
                                ? "Easy"
                                : this.state.view.complexity_code === 2
                                  ? "Medium"
                                  : "Hard"}
                            </Avatar>
                          </div>

                          {/* Author */}
                          <div>
                            <h4 style={{ marginBottom: 8 }}>Author</h4>
                            <Avatar
                              shape="square"
                              size="large"
                              style={{
                                backgroundColor: "#1677ff",
                                color: "#fff",
                                fontWeight: 500,
                              }}
                            >
                              {this.state.view.author_name || "Unknown"}
                            </Avatar>
                          </div>

                          {/* Explanation */}
                          <div>
                            <h4 style={{ marginBottom: 8 }}>Explanation</h4>
                            <div
                              style={{
                                background: "#fff",
                                padding: "12px",
                                borderRadius: "10px",
                                boxShadow: "0 2px 6px rgba(0,0,0,0.04)",
                                minHeight: "60px",
                                color: "#333",
                              }}
                            >
                              {this.state.view.answer_explanation || "No explanation provided."}
                            </div>
                          </div>
                        </Space>
                      </Drawer>
                    </div>
                  </div>

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

    return (
      <Layout style={{ minHeight: "100vh", backgroundColor: "#f0f2f5" }}>
        <Siderc />
        <Layout>
          <Headerc />
          <Content
            style={{
              padding: "32px",
              backgroundColor: "#f0f2f5",
            }}
          >
            {/* PAGE HEADER */}
            <div
              style={{
                fontSize: "24px",
                fontWeight: 700,
                marginBottom: "24px",
                color: "#1a1a1a",
                textAlign: "center",
                letterSpacing: "0.3px",
              }}
            >
              {this.state.examName} — Report
            </div>

            {/* OVERALL SECTION */}
            <div
              style={{
                backgroundColor: "#F5F7FA",
                borderRadius: "16px",
                padding: "32px 24px",
                boxShadow: "inset 0 0 6px rgba(0,0,0,0.05)",
                marginBottom: "40px",
              }}
            >
              <Row gutter={[24, 24]} justify="center" align="middle">
                {/* SCORE CARD */}
                <Col xs={24} sm={12} md={10}>
                  <div
                    style={{
                      background: "#fff",
                      borderRadius: "12px",
                      padding: "24px",
                      boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                      borderTop: "4px solid #1677ff",
                      transition: "transform 0.2s ease",
                      overflow: "hidden",
                    }}
                    onMouseEnter={(e) =>
                      (e.currentTarget.style.transform = "translateY(-4px)")
                    }
                    onMouseLeave={(e) =>
                      (e.currentTarget.style.transform = "translateY(0)")
                    }
                  >
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        marginBottom: "16px",
                      }}
                    >
                      <h3
                        style={{
                          fontSize: "18px",
                          fontWeight: 600,
                          display: "flex",
                          alignItems: "center",
                          gap: "8px",
                          color: "#1677ff",
                        }}
                      >
                        <DashboardOutlined />
                        Score
                      </h3>
                      <span
                        style={{
                          fontSize: "20px",
                          fontWeight: 700,
                          color: "#1a1a1a",
                        }}
                      >
                        {this.state.totalMarksReceived}/{this.state.totalMarks}
                      </span>
                    </div>

                    <Plot
                      data={[
                        {
                          type: "bar",
                          x: secNames,
                          y: secMarks,
                          orientation: "v",
                          marker: { color: "#1677ff" },
                        },
                      ]}
                      layout={{
                        height: 250,
                        margin: { l: 40, r: 10, t: 10, b: 40 },
                        yaxis: {
                          range: [
                            this.state.total_least_mark,
                            this.state.total_max_mark,
                          ],
                          showgrid: false,
                          zeroline: false,
                          showline: false,
                        },
                        xaxis: { tickfont: { size: 12 } },
                        showlegend: false,
                        paper_bgcolor: "rgba(0,0,0,0)",
                        plot_bgcolor: "rgba(0,0,0,0)",
                      }}
                      config={{ displayModeBar: false, responsive: true }}
                      style={{ width: "100%" }}
                    />
                  </div>
                </Col>

                {/* ACCURACY CARD */}
                <Col xs={24} sm={12} md={10}>
                  <div
                    style={{
                      background: "#fff",
                      borderRadius: "12px",
                      padding: "24px",
                      boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                      borderTop: "4px solid #52c41a",
                      transition: "transform 0.2s ease",
                      overflow: "hidden",
                    }}
                    onMouseEnter={(e) =>
                      (e.currentTarget.style.transform = "translateY(-4px)")
                    }
                    onMouseLeave={(e) =>
                      (e.currentTarget.style.transform = "translateY(0)")
                    }
                  >
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        marginBottom: "16px",
                      }}
                    >
                      <h3
                        style={{
                          fontSize: "18px",
                          fontWeight: 600,
                          display: "flex",
                          alignItems: "center",
                          gap: "8px",
                          color: "#52c41a",
                        }}
                      >
                        <PieChartOutlined />
                        Accuracy
                      </h3>
                      <span
                        style={{
                          fontSize: "20px",
                          fontWeight: 700,
                          color: "#52c41a",
                        }}
                      >
                        {percentage.toFixed(1)}%
                      </span>
                    </div>

                    <Plot
                      data={[
                        {
                          type: "pie",
                          values: [
                            this.state.total_correct_answer,
                            this.state.total_wrong_answer,
                            this.state.total_notAttempted_answer,
                          ],
                          labels: ["Correct", "Incorrect", "Not Attempted"],
                          marker: {
                            colors: ["#52c41a", "#ff4d4f", "#d9d9d9"],
                          },
                          textinfo: "label+percent",
                          hoverinfo: "label+value",
                          hole: 0.4,
                        },
                      ]}
                      layout={{
                        height: 250,
                        width: 350,
                        margin: { t: 60, b: 60, l: 60, r: 60 },
                        showlegend: true,
                        legend: {
                          orientation: "h",
                          y: -0.2,
                          font: { size: 12 },
                        },
                        paper_bgcolor: "rgba(0,0,0,0)",
                        plot_bgcolor: "rgba(0,0,0,0)",
                      }}
                      config={{ displayModeBar: false, responsive: true }}
                    />
                  </div>
                </Col>
              </Row>
            </div>

            {/* SECTION TABS */}
            <div className="SectionTabPane" style={{ marginTop: "32px" }}>
              {tabs}
            </div>
          </Content>
        </Layout>
      </Layout>
    );

  }
}

export default Report;
