import React from "react";
import "./LiveExams.css";
import {
  Layout,
  List,
  Avatar,
  Button,
  Card,
  Tag,
  Typography,
  Space,
} from "antd";
import {
  AppstoreOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons";
import "antd/dist/antd.css";
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";

const { Content } = Layout;
const { Title, Text } = Typography;

class LiveExams extends React.Component {
  state = {
    currentUser: authenticationService.currentUserValue,
    batch: "1",
    data: [],
    total_count: 0,
    layout: "card", // 'card' or 'detail'
  };

  componentDidMount() {
    this.loadExams(1);
  }

  loadExams = (pageNumber) => {
    const json = {
      pageSize: 10,
      pageNumber,
      batch: JSON.parse(sessionStorage.getItem("currentUser"))?.batch_id || null,
    };

    selectorService.loadLiveExams(json).then((data1) => {
      const result = data1?.result || {};
      const exams = result.exams || [];
      const formattedData = exams.map((exam, index) => {
        const start = new Date(exam.start_date);
        const end = new Date(exam.end_date);
        const daysLeft = Math.floor(
          (end.getTime() - new Date().getTime()) / (1000 * 3600 * 24)
        );
        return {
          key: index,
          id: exam.id,
          name: exam.name,
          subject: exam.subject_name,
          marks: exam.total_marks,
          questions: exam.total_questions,
          duration: exam.exam_duration / 60,
          startDate: start.toLocaleDateString(),
          endDate: end.toLocaleDateString(),
          daysLeft,
          attemptStatus: exam.attempt_status,
        };
      });

      this.setState({
        data: formattedData,
        total_count: result.total_count,
      });
    });
  };

  render() {
    const { data, total_count, layout } = this.state;

    return (
      <Layout>
        <Siderc />
        <Layout>
          <Headerc />
          <Content
            style={{
              padding: "24px",
              background: "#f0f3f8", // same as topbar
              minHeight: "100vh",
            }}
          >
            {/* Header + Buttons */}
            <Space
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: 20,
              }}
            >
              <Title level={3} style={{ margin: 0, color: "#222", fontWeight: 600 }}>
                🎯 Live Exams
              </Title>

              <Button.Group>
                <Button
                  type={layout === "card" ? "primary" : "default"}
                  icon={<AppstoreOutlined />}
                  onClick={() => this.setState({ layout: "card" })}
                >
                  Card View
                </Button>
                <Button
                  type={layout === "detail" ? "primary" : "default"}
                  icon={<UnorderedListOutlined />}
                  onClick={() => this.setState({ layout: "detail" })}
                >
                  Detail View
                </Button>
              </Button.Group>
            </Space>

            {/* Card Layout */}
            {layout === "card" ? (
              <List
                grid={{
                  gutter: 24,
                  xs: 1,
                  sm: 1,
                  md: 2,
                  lg: 2,
                  xl: 3,
                }}
                pagination={{
                  pageSize: 10,
                  total: total_count,
                  onChange: (page) => this.loadExams(page),
                }}
                dataSource={data}
                renderItem={(item) => (
                  <List.Item>
                    <Card
                      hoverable
                      bordered={false}
                      style={{
                        borderRadius: 12,
                        background: "#ffffff",
                        boxShadow:
                          "0 2px 8px rgba(0,0,0,0.08), 0 4px 16px rgba(0,0,0,0.06)",
                        transition: "all 0.2s ease-in-out",
                      }}
                    >
                      <Space direction="vertical" size="small" style={{ width: "100%" }}>
                        {/* Top Section: Avatar + Title + Days Left */}
                        <Space align="center" style={{ width: "100%", justifyContent: "flex-start" }}>
                          <Avatar
                            src={`https://s3bucket-for-oa.s3.ap-south-1.amazonaws.com/${9}/exams/${item.id}.png`}
                            size={64}
                            shape="square"
                          />
                          <div style={{ flex: 1, marginLeft: 10 }}>
                            {/* Exam Name + Days Left Inline */}
                            <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap" }}>
                              <Title
                                level={5}
                                style={{
                                  margin: 0,
                                  color: "#222",
                                  fontWeight: 600,
                                  display: "inline-block",
                                }}
                              >
                                {item.name}
                              </Title>

                              <Tag
                                color={
                                  item.daysLeft <= 0
                                    ? "red"
                                    : item.daysLeft < 3
                                      ? "orange"
                                      : "green"
                                }
                                style={{
                                  marginLeft: 10,
                                  fontSize: 13,
                                  padding: "0 8px",
                                  height: 22,
                                  display: "flex",
                                  alignItems: "center",
                                }}
                              >
                                {item.daysLeft > 0 ? `${item.daysLeft} days left` : "Ended"}
                              </Tag>
                            </div>

                            <Text type="secondary">{item.subject}</Text>
                          </div>
                        </Space>

                        {/* Exam Details */}
                        <Space
                          direction="vertical"
                          style={{
                            marginTop: "10px",
                            fontSize: "14px",
                            color: "#444",
                          }}
                        >
                          <div>
                            <Text strong>Start:</Text> {item.startDate}
                          </div>
                          <div>
                            <Text strong>End:</Text> {item.endDate}
                          </div>
                          <div>
                            <Text strong>Duration:</Text> {item.duration} mins
                          </div>
                          <div>
                            <Text strong>Questions:</Text> {item.questions}
                          </div>
                          <div>
                            <Text strong>Marks:</Text> {item.marks}
                          </div>
                        </Space>

                        {/* Buttons */}
                        <Space style={{ marginTop: 12 }}>
                          <Link
                            to={{
                              pathname: "/instructions",
                              state: { examId: item.id, duration: item.duration, totalQuestions: item.questions, totalMarks: item.marks, startDate: item.startDate, endDate: item.endDate, examName: item.name, daysLeft: item.daysLeft },
                            }}
                          >
                            <Button type="primary">
                              {item.attemptStatus === "Pause" ? "Resume" : "Start Exam"}
                            </Button>
                          </Link>

                          {item.attemptStatus === "Completed" && (
                            <Link to={{ pathname: "/report", state: { examId: item.id } }}>
                              <Button>View Report</Button>
                            </Link>
                          )}
                        </Space>
                      </Space>
                    </Card>
                  </List.Item>
                )}
              />

            ) : (
              // Detail Layout (Horizontal Cards)
              <List
                itemLayout="horizontal"
                dataSource={data}
                pagination={{
                  pageSize: 10,
                  total: total_count,
                  onChange: (page) => this.loadExams(page),
                }}
                renderItem={(item) => (
                  <List.Item style={{ padding: "12px 0" }}>
                    <Card
                      bordered={false}
                      style={{
                        width: "100%",
                        borderRadius: 12,
                        background: "#ffffff",
                        boxShadow:
                          "0 2px 8px rgba(0,0,0,0.08), 0 4px 16px rgba(0,0,0,0.06)",
                      }}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          width: "100%",
                        }}
                      >
                        {/* Left Section - Image + Details */}
                        <Space align="start">
                          <Avatar
                            src={`https://s3bucket-for-oa.s3.ap-south-1.amazonaws.com/${9}/exams/${item.id}.png`}
                            size={80}
                            shape="square"
                          />

                          <div style={{ flex: 1, marginLeft: 16 }}>
                            {/* Title + Days Left Tag close together */}
                            <div
                              style={{
                                display: "flex",
                                alignItems: "center",
                                flexWrap: "wrap",
                              }}
                            >
                              <Title level={5} style={{ margin: 0, color: "#222" }}>
                                {item.name}
                              </Title>

                              <Tag
                                color={
                                  item.daysLeft <= 0
                                    ? "red"
                                    : item.daysLeft < 3
                                      ? "orange"
                                      : "green"
                                }
                                style={{ marginLeft: 10, fontSize: 13 }}
                              >
                                {item.daysLeft > 0
                                  ? `${item.daysLeft} days left`
                                  : "Ended"}
                              </Tag>
                            </div>

                            <Text type="secondary">{item.subject}</Text>

                            <div style={{ marginTop: 8, fontSize: 14 }}>
                              <Text strong>Start:</Text> {item.startDate}{" "}
                              <Text strong style={{ marginLeft: 16 }}>
                                End:
                              </Text>{" "}
                              {item.endDate}{" "}
                              <Text strong style={{ marginLeft: 16 }}>
                                Duration:
                              </Text>{" "}
                              {item.duration} mins{" "}
                              <Text strong style={{ marginLeft: 16 }}>
                                Questions:
                              </Text>{" "}
                              {item.questions}{" "}
                              <Text strong style={{ marginLeft: 16 }}>
                                Marks:
                              </Text>{" "}
                              {item.marks}
                            </div>
                          </div>
                        </Space>

                        {/* Right Section - Centered Buttons */}
                        <div
                          style={{
                            display: "flex",
                            flexDirection: "column",
                            alignItems: "center",
                            justifyContent: "center",
                            minWidth: 120,
                          }}
                        >
                          <Space>
                            <Link
                              to={{
                                pathname: "/instructions",
                                state: { examId: item.id, duration: item.duration, totalQuestions: item.questions, totalMarks: item.marks, startDate: item.startDate, endDate: item.endDate, examName: item.name, daysLeft: item.daysLeft },
                              }}
                            >
                              <Button type="primary">
                                {item.attemptStatus === "Pause" ? "Resume" : "Start Exam"}
                              </Button>
                            </Link>

                            {item.attemptStatus === "Completed" && (
                              <Link to={{ pathname: "/report", state: { examId: item.id } }}>
                                <Button>View Report</Button>
                              </Link>
                            )}
                          </Space>
                        </div>
                      </div>
                    </Card>
                  </List.Item>
                )}
              />
            )}
          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default LiveExams;
