import {
  Steps,
  Button,
  message,
  Layout,
  List,
  Avatar,
  Skeleton,
  Empty,
  Image,
  notification,
} from "antd";
import "./DraftExam.css";
import { Siderc } from "../Main/Siderc";
import React from "react";
import { Headerc } from "../Main/Headerc";
import { Link } from "react-router-dom";
import history from "../../history";
import { selectorService } from "../../services/selectorService";
import parse from "html-react-parser";
import { S3_BUCKET_EXAM_PREFIX } from "../../_services/config";

const { Content } = Layout;

class UpcomingExam extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      total_count: 0,
      total_pages: 0,
      processing: true,
    };
  }
  componentDidMount() {
    selectorService
      .upcomingExam({
        pageSize: 10,
        pageNumber: 1,
        classId: parseInt(sessionStorage.getItem("currentClass")),
      })
      .then((res) => {
        // console.log(res);
        if(res.status.code === "-1") {
          throw "Something went wrong, please reload."
        }
        this.setState({
          data: res?.result.exams,
          total_count: res?.result.total_count,
          total_pages: res?.result.total_pages,
          processing: false,
        })
      })
      .catch((err) => {
        console.error(err);
        notification.error({
          message: "Error!!!",
          description: err,
          duration: 10
        })
      });
  }

  handleChange = (pageNumber, pageSize) => {
    selectorService
      .upcomingExam({ pageNumber: pageNumber, pageSize: pageSize, classId: 1 })
      .then((res) => {
        if(res) {
          this.setState({
          data: res?.result.exams,
          total_count: res?.result.total_count,
          total_pages: res?.result.total_pages,
          processing: false,
        })}
      })
      .catch((err) => {
        console.log(err);
      });
  };

  render() {
    if (this.state.data.length !== 0)
      return (
        <Layout>
          <Siderc />
          <Layout>
            <Headerc />
            <Content
              className="site-layout-background"
              style={{
                padding: 24,
                margin: 0,
              }}
            >
              <Layout className="createExamLayoutHeader">Upcoming Exams</Layout>
              <Layout className="createExamLayout">
                <List
                  itemLayout="horizontal"
                  dataSource={this.state.data}
                  pagination={{
                    onChange: (page, pageSize) => {
                      this.handleChange(page, pageSize);
                    },

                    total: this.state.total_count,
                  }}
                  renderItem={(item, index) => {
                    let step = 2;
                    if (item.sections_count >= 1) step = 3;
                    if (item.sections_status !== "DRAFT") step = 4;
                    let currentTime = new Date();
                    let loginTime = new Date(item.updated_on);
                    const diff = currentTime.getTime() - loginTime.getTime();
                    // console.log(diff,loginTime,currentTime,item.updated_on);
                    var years = Math.floor(
                      diff / (1000 * 60 * 60 * 24 * 30 * 12)
                    );
                    var months = Math.floor(
                      (diff % (1000 * 60 * 60 * 24 * 30 * 12)) /
                        (1000 * 60 * 60 * 24 * 30)
                    );
                    var days = Math.floor(
                      (diff % (1000 * 60 * 60 * 24 * 30)) /
                        (1000 * 60 * 60 * 24)
                    );

                    var hours = Math.floor(
                      (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
                    );
                    var minutes = Math.floor((diff % 3.6e6) / 6e4);
                    let updatedOn =
                      years > 0
                        ? `${years} year(s)/${months} months`
                        : months > 0
                        ? `${months} month(s)/${days} days`
                        : days > 0
                        ? `${days} day(s)/${hours} hours`
                        : minutes > 0
                        ? `${hours} hour(s)${minutes}minutes(s)`
                        : minutes + "minutes";
                    console.log(item);
                    return (
                      <List.Item
                        className="DraftExam"
                        key={index}
                        actions={[
                          <Button
                            onClick={(e, newValue) => {
                              console.log(item, e);
                            }}
                            type="primary"
                          >
                            <Link
                              to={{
                                pathname: "/associateBatch",
                                state: {
                                  id: item.id,
                                  current: step - 1,
                                  start_date: item.start_date,
                                  end_date: item.end_date,
                                  exam_duration: item.exam_duration,
                                  total_questions: item.exam_duration,
                                  total_marks: item.total_marks,
                                  name: item.name,
                                },
                              }}
                            >
                              Associate Batch
                            </Link>
                          </Button>,
                        ]}
                      >
                        <List.Item.Meta
                          avatar={
                            <Image
                              // src="https://cdn.xl.thumbs.canstockphoto.com/exam-written-on-a-chalkboard-books-pencils-and-an-apple-on-foreground-picture_csp2468961.jpg"
                              src={`${S3_BUCKET_EXAM_PREFIX+item.id}.png`}
                              fallback="https://cdn.xl.thumbs.canstockphoto.com/exam-written-on-a-chalkboard-books-pencils-and-an-apple-on-foreground-picture_csp2468961.jpg"
                              // size="large"
                              // shape="square"
                              width={100}
                              height={100}
                              className="DraftExamImage"
                            />
                          }
                          size="large"
                          bordered="true"
                          title={item.name}
                          description={
                            <>
                              <div className="MyExamDiv">
                                <table>
                                  <thead>
                                    <tr>
                                      <th>Start Date</th>
                                      <th>End Date</th>
                                      <th>Durations</th>
                                      <th>Questions</th>
                                      <th>Marks</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    <tr>
                                      <td>{item.start_date}</td>
                                      <td>{item.end_date}</td>
                                      <td>{item.exam_duration}</td>
                                      <td>{item.total_questions}</td>
                                      <td>{item.total_marks}</td>
                                    </tr>
                                  </tbody>
                                </table>
                              </div>
                            </>
                          }
                        />
                        {/* <div className="MyExamDiv">
                          <table>
                            <thead>
                              <tr>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Subject</th>
                                <th>Durations</th>
                                <th>Questions</th>
                                <th>Marks</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>{item.start_date}</td>
                                <td>{item.end_date}</td>
                                <td>{item.exam_duration}</td>
                                <td>{item.exam_duration}</td>
                                <td>{item.total_questions}</td>
                                <td>{item.total_marks}</td>
                              </tr>
                            </tbody>
                          </table>
                        </div> */}
                      </List.Item>
                    );
                  }}
                />
              </Layout>
            </Content>
          </Layout>
        </Layout>
      );
    else if (this.state.processing)
      return (
        <>
          <Layout>
            <Siderc />
            <Layout>
              <Headerc />

              <Content
                className="site-layout-background"
                style={{
                  padding: 24,
                  margin: 0,
                }}
              >
                <Layout className="createExamLayoutHeader">
                  Upcoming Exams
                </Layout>
                <Layout className="createExamLayout">
                  <List
                    itemLayout="horizontal"
                    dataSource={[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]}
                    pagination={{
                      onChange: (page, pageSize) => {
                        this.handleChange(page, pageSize);
                      },

                      total: this.state.total_count,
                    }}
                    renderItem={(item, index) => {
                      // let step = 2;
                      // if (item.sections_count >= 1) step = 3;
                      // if (item.sections_status !== "DRAFT") step = 4;
                      // let currentTime = new Date();
                      // let loginTime = new Date(item.updated_on);
                      // const diff = currentTime.getTime() - loginTime.getTime();
                      // // console.log(diff,loginTime,currentTime,item.updated_on);
                      // var years = Math.floor(diff / (1000 * 60 * 60 * 24 * 30 * 12));
                      // var months = Math.floor(
                      //   (diff % (1000 * 60 * 60 * 24 * 30 * 12)) / (1000 * 60 * 60 * 24 * 30),
                      // );
                      // var days = Math.floor(
                      //   (diff % (1000 * 60 * 60 * 24 * 30)) / (1000 * 60 * 60 * 24),
                      // );

                      // var hours = Math.floor(diff%(1000*60*60*24) / (1000 * 60 * 60));
                      // var minutes=Math.floor((diff % 3.6e+6) / 6e+4);
                      // let updatedOn=
                      // years > 0
                      //   ? `${years} year(s)/${months} months`
                      //   : months > 0
                      //   ? `${months} month(s)/${days} days`
                      //   : days > 0
                      //   ? `${days} day(s)/${hours} hours`
                      //   :minutes>0? `${hours} hour(s)${minutes}minutes(s)`:minutes+'minutes';
                      return (
                        <List.Item
                          className="DraftExam"
                          key={index}
                          // actions={[
                          //   <Button
                          //     onClick={(e, newValue) => {
                          //       console.log(item, e);
                          //     }}
                          //     type="primary"
                          //   >
                          //     <Link
                          //       to={{
                          //         pathname: "/createExam",
                          //         state: { id: item.id, current: step - 1 },
                          //       }}
                          //     >
                          //       Recreate Exam
                          //     </Link>
                          //   </Button>,
                          // ]}
                        >
                          <Skeleton>
                            <List.Item.Meta
                              avatar={
                                <Avatar
                                  src="https://cdn.xl.thumbs.canstockphoto.com/exam-written-on-a-chalkboard-books-pencils-and-an-apple-on-foreground-picture_csp2468961.jpg"
                                  size="large"
                                  shape="square"
                                  className="DraftExamImage"
                                />
                              }
                              size="large"
                              bordered="true"
                              title={parse(`<b>${"item.name"}</b>`)}
                              description={parse(
                                `<b>Progress - Step</b> ${"step"} <b>Updated At:</b> ${"updatedOn"}  <b>Author Name:</b> ${"item.author_name"} <b>Sections Count: </b>${"item.sections_count"}`
                              )}
                            />
                          </Skeleton>
                        </List.Item>
                      );
                    }}
                  />
                </Layout>
              </Content>
            </Layout>
          </Layout>
        </>
      );
    else
      return (
        <>
          <Layout>
            <Siderc />
            <Layout>
              <Headerc />

              <Content
                className="site-layout-background"
                style={{
                  padding: 24,
                  margin: 0,
                }}
              >
                <Layout className="createExamLayoutHeader">
                  Upcoming Exams
                </Layout>
                <Layout className="createExamLayout">
                  <Empty />
                </Layout>
              </Content>
            </Layout>
          </Layout>
        </>
      );
  }
}

export default UpcomingExam;
