import React, { useState, useEffect } 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/FuncHeader";
import { selectorService } from "../../../../services/selectorService";
import { Link } from "react-router-dom";

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

const LiveExams = () => {
  const [classLoading, setClassLoading] = useState(true);
  const [language, setLanguage] = useState([]);
  const [data, setData] = useState([]);
  const [layout, setLayout] = useState("card");
  const [totalCount, setTotalCount] = useState(0);
  const currentUser = authenticationService.currentUserValue;

  useEffect(() => {
    loadExams(1);
  }, []);

  const 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,
          attemptsTaken: exam.attempts_taken,
        };
      });

      setData(formattedData);
      setTotalCount(result.total_count);
      setClassLoading(false);
    });
  };

  return (
    <Layout>
      <Siderc />
      <Layout>
        <Headerc title={"🎯 Live Exams"} location={{ pathname: "/liveExams" }}
          isClassLoading={classLoading} setLanguage={setLanguage} />
        <Content
          style={{
            padding: "24px",
            background: "#f0f3f8",
            minHeight: "100vh",
          }}
        >
          {/* Header + Buttons */}
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              alignItems: "center",
              marginBottom: 20,
              width: "100%",
            }}
          >
            <Button.Group>
              <Button
                type={layout === "card" ? "primary" : "default"}
                icon={<AppstoreOutlined />}
                onClick={() => setLayout("card")}
              >
                Card View
              </Button>
              <Button
                type={layout === "detail" ? "primary" : "default"}
                icon={<UnorderedListOutlined />}
                onClick={() => setLayout("detail")}
              >
                Detail View
              </Button>
            </Button.Group>
          </div>

          {/* Card Layout */}
          {layout === "card" ? (
            <List
              grid={{
                gutter: 24,
                xs: 1,
                sm: 1,
                md: 2,
                lg: 2,
                xl: 3,
              }}
              pagination={{
                pageSize: 10,
                total: totalCount,
                onChange: (page) => 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 */}
                      <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 }}>
                          <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.attemptsTaken > 0 && (
                          <Link
                            to={{
                              pathname: "/report",
                              state: { examId: item.id },
                            }}
                          >
                            <Button>View Report</Button>
                          </Link>
                        )}
                      </Space>
                    </Space>
                  </Card>
                </List.Item>
              )}
            />
          ) : (
            // Detail Layout
            <List
              itemLayout="horizontal"
              dataSource={data}
              pagination={{
                pageSize: 10,
                total: totalCount,
                onChange: (page) => 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%",
                      }}
                    >
                      <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 }}>
                          <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>

                      <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.attemptsTaken > 0 && (
                            <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;
