import { message, Layout, Row, Col, Drawer, Tree, Typography } from "antd";
import { confirmAlert } from "react-confirm-alert"; // Import
import "react-confirm-alert/src/react-confirm-alert.css"; // Import css
import React from "react";
import "./CreateClass.css";
import { DownOutlined, LoadingOutlined } from "@ant-design/icons";
import { selectorService } from "../../services/selectorService";

import Lmao from "./Lmao";

const { Content } = Layout;

class ViewClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      batchName: "",
      batches: [],
      step: 1,
      mockData: [],
      targetKeys: [],
      currentIndex: "",
      visible: false,
      subjects: [],
      pageLoading: true
    };
  }
  componentDidMount() {
    // console.log(this.props);
    this.setState(prev => ({ ...prev, pageLoading: true }));
    selectorService.getAllClass().then((res) => {
      let batches = res.result;
      // console.log(batches);
      if (this.props.location.state) {
        selectorService.getClassDetails(this.props.location.state).then((res) => {
          // console.log(res);
          let currentIndex = "";
          batches.map((x, idx) => {
            currentIndex = x.id === this.props.location.state ? idx : currentIndex;
          });
          // console.log(currentIndex);
          this.setState({
            batches,
            visible: true,
            subjects: res.result.subjects,
            currentIndex,
            pageLoading: false
          });
        })
          .catch((err) => {
            console.log(err);
            this.setState(prev => ({ ...prev, pageLoading: false }));
          });
      } else {
        this.setState({
          batches,
          pageLoading: false
        });
      }
    })
      .catch((err) => {
        console.log(err);
        this.setState(prev => ({ ...prev, pageLoading: false }));
      });
  }

  handleDeleteButton = (index, name) => {
    confirmAlert({
      title: "Confirm to delete",
      message: "Are you sure you want to delete \"" + name + "\" class",
      buttons: [
        {
          label: "Yes",
          onClick: () => {
            this.setState(prev => ({ ...prev, loadingState: true }));
            selectorService.deleteClass(this.state.batches[index].id).then((res) => {
              if (+res.status.code < 0) {
                throw "Operation failed, could not delete the batch"
              }
              let batches = this.state.batches.filter((y) => y.id !== this.state.batches[index].id);
              this.setState({ batches, loadingState: false }, () => {
                message.success("Deleted Successfully");
              });
            }).catch((err) => {
              console.log(err);
              message.error(err);
            });
          },
        },
        {
          label: "No",
          onClick: () => { },
        },
      ],
    });
  }

  handleViewButton = (id, arrayIdx) => {
    // console.log("here");
    this.setState(prev => ({ ...prev, pageLoading: true }));
    selectorService.getClassDetails(id)
      .then((res) => {
        // console.log(res);
        if(+res.status.code < 0) {
          throw res.status.message[0];
        }
        this.setState({
          currentIndex: arrayIdx,
          visible: true,
          subjects: res.result.subjects,
          pageLoading: false
        });
      })
      .catch((err) => {
        console.log(err);
        this.setState(prev => ({ ...prev, pageLoading: false }));
      }
      );
  }

  //   componentDidUpdate(prevprops) {
  //     if (!isEqual(this.props.location, prevprops.location)) console.log("here");
  //   }

  render() {
    let treeData = [
      {
        title:
          typeof this.state.currentIndex !== "string" &&
            this.state.batches.length >= this.state.currentIndex + 1
            ? `${this.state.batches[this.state.currentIndex].name}`
            : "",
        key: "0",
        children: [],
      },
    ];
    treeData[0].children = this.state.subjects.map((x, idx) => {
      return {
        title: x.name,
        key: "0" + idx,
        children: x.topics.map((y, idxY) => {
          return {
            title: y.name,
            key: "0" + idx + idxY,
          };
        }),
      };
    });

    if (this.state.pageLoading) {
      return (<div className="center-flex mt-2-0"><LoadingOutlined style={{ fontSize: 32 }} spin /></div>)
    }

    return (
      <Content className="site-layout-background" style={{ padding: 24, margin: 0 }}>
        <Drawer
          title={
            typeof this.state.currentIndex !== "string" &&
              this.state.batches.length >= this.state.currentIndex + 1
              ? `${this.state.batches[this.state.currentIndex].name}`
              : ""
          }
          placement="right"
          closable={false}
          onClose={() => {
            this.setState({ visible: false, currentIndex: "", pageLoading: false });
          }}
          visible={this.state.visible}
        >
          <div className="center-flex"><Typography.Text type={"secondary"}>Class syllabus as follows:</Typography.Text></div>
          <Tree
            showLine
            switcherIcon={<DownOutlined />}
            onSelect={this.onSelect}
            treeData={treeData}
          />
        </Drawer>
        <Row>
          {this.state.batches.map((x, idx) => {
            if (idx % 4 === 0)
              return (
                <Col span={5} key={`${x.name.substring(0, 4)}-${idx}`}>
                  <Lmao viewState={this.state.currentIndex === idx} details={x} viewButton={this.handleViewButton} classTitle={x.name} idx={idx} deleteButton={this.handleDeleteButton} />
                </Col>
              );
            else
              return (
                <Col span={5} offset={1} key={`${x.name.substring(0, 4)}-${idx}`}>
                  <Lmao viewState={this.state.currentIndex === idx} details={x} viewButton={this.handleViewButton} classTitle={x.name} idx={idx} deleteButton={this.handleDeleteButton} />
                </Col>
              );
          })}
        </Row>
      </Content>
    );
  }
}

export default ViewClass;
