import { message, Layout, Row, Col, Empty, Modal, Typography, Avatar } from "antd";
import { confirmAlert } from "react-confirm-alert"; // Import
import "react-confirm-alert/src/react-confirm-alert.css"; // Import css
import React, { useEffect, useRef, useState, useMemo } from "react";
import "./CreateBatch.css";
import { LoadingOutlined, UserOutlined } from "@ant-design/icons";
import { selectorService } from "../../services/selectorService";
import BatchCard from "./BatchCard";

const { Content } = Layout;

class CreateBatch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      batchName: "",
      batches: [],
      step: 1,
      mockData: [],
      targetKeys: [],
      visible: false,
      viewingIndex: -1,
      info: [],
      loadingState: true
    };
  }
  componentDidMount() {
    this.setState(prev => ({ ...prev, loadingState: true }));
    selectorService.getAllBatch({ class_id: sessionStorage.getItem("currentClass") })
      .then((res) => {
        let batches = res.result;
        this.setState(prev => ({ ...prev, batches, loadingState: false }));
      })
      .catch((err) => {
        console.log(err);
        this.setState(prev => ({ ...prev, loadingState: false }));
      });
  }

  handleDeleteButton = (index, name, student_count) => {
    confirmAlert({
      title: "Confirm to delete",
      message: student_count === 0 ? "Are you sure you want to delete " + name + " batch?"
        : name + " consists of students. Are you sure you want to delete this batch?",
      buttons: [
        {
          label: "Yes",
          onClick: () => {
            this.setState(prev => ({ ...prev, loadingState: true }));
            selectorService.deleteBatch(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);
              this.setState({ loadingState: false });
            });
          },
        },
        {
          label: "No",
          onClick: () => { },
        },
      ],
    });
  }

  closeModal = () => {
    this.setState(prev => ({...prev, visible: false, viewingIndex: -1}));
  }

  openModal = (details) => {
    this.setState(prev => ({...prev, viewingIndex: details.id, info: [{...details}], visible: true}));
  }

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

    return (
      <Content className="site-layout-background" style={{ padding: 24, margin: 0 }}>
        <Row>
          {this.state.batches.map((x, idx) => {
            if (idx % 3 === 0)
              return (
                <Col span={7} key={`${x.name.substring(0, 4)}-${idx}`}>
                  <BatchCard key={x.name} details={this.state.batches[idx]} idx={idx} batchTitle={x.name} 
                    studentNumber={x.student_count} handleDelete={this.handleDeleteButton} 
                    onView={this.openModal} />
                </Col>
              );
            else
              return (
                <Col span={7} offset={1} key={`${x.name.substring(0, 4)}-${idx}`}>
                  <BatchCard key={x.name} details={this.state.batches[idx]} idx={idx} batchTitle={x.name} 
                    studentNumber={x.student_count} handleDelete={this.handleDeleteButton}
                    onView={this.openModal} />
                </Col>
              );
          })}
          {this.state.batches?.length === 0 && (
            <div style={{ width: "100%" }}>
              <Empty />
            </div>
          )}
        </Row>
        <Modal title={"Batch Explorer"} destroyOnClose={true} width={"auto"}
          placement="right" onCancel={() => this.closeModal()} visible={this.state.visible} footer={null}>
            <BatchExplorer key={this.state.viewingIndex} id={this.state.viewingIndex} close={this.closeModal} info={this.state.info[0]}/>
        </Modal>
      </Content>
    );
  }
}

function BatchExplorer({id = -1, close, info}) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const mounted = useRef(true);

  const updatedOn = useMemo(() => (new Date(info.updated_on)), [info.updated_on]);

  useEffect(() => {
    if(id != -1) fetchStudentsOfBatch();
    return () => mounted.current = false;
  }, []);

  async function fetchStudentsOfBatch() {
    try {
      const res = await selectorService.getStudentsOfBatch(id);
      if(+res.status.code < 0) {
        throw res.status.message[0];
      }
      if(Array.isArray(res.result) && res.result.length > 0) {
        setData([...res.result]);
      }
      setLoading(false);
    } catch (error) {
      console.log(error);
      setLoading(false);
    }
  }

  if(id === -1) {
    close();
  }
  if(loading) {
    return <LoadingOutlined spin />
  }
  return <>
    <div className="dudes-of-batch">
      <div className="basic-info">
        <Typography.Paragraph key={"batch-name"}>Batch Name - <Typography.Text strong>{info.name}</Typography.Text></Typography.Paragraph>
        <Typography.Paragraph key={"student-no."}>No. of students - <Typography.Text strong>{info.student_count}</Typography.Text></Typography.Paragraph>
        <Typography.Paragraph key={"updated-on"}>Last updated on - <Typography.Text strong>{updatedOn.toDateString()}</Typography.Text></Typography.Paragraph>
      </div>
      {
        !data || data.length === 0? <><Typography.Paragraph>Student Record:</Typography.Paragraph><Empty /></>
        : 
          <div className="records"><Typography.Paragraph>Student Record:</Typography.Paragraph>
          <div className="dude-pool">
          {data.map((student, index) => {
            const emailArray = student?.email_id.split("@");
            return <div key={"student-"+index} className="each-dude">
              <span>
                <Avatar size={64} src={student.photo? student.photo : null} icon={<UserOutlined />} /> 
              </span>
              <span>
                <Typography.Text key={"student-name-"+index}>Name: </Typography.Text> 
                {student.first_name || student.last_name? <Typography.Paragraph key={"name-"+index} strong 
                  ellipsis={{rows: 2, tooltip: `${student?.first_name} ${student?.last_name}`}}>
                    {student?.first_name} {student?.last_name}
                  </Typography.Paragraph>
                  : <Typography.Paragraph type={"warning"} key={"no-name-"+index} strong>No Name given</Typography.Paragraph>}
              </span>
              <span>
                <Typography.Text key={"email-"+index}>Email ID: </Typography.Text>
                {student.email_id && <Typography.Paragraph style={{marginBottom: 0, width: 155}} key={"mail-id-"+index} ellipsis={{tooltip: emailArray[0]}} strong>{emailArray[0]}</Typography.Paragraph>}
                {student.email_id && <Typography.Paragraph key={"domain-"+index} type={"secondary"} strong>
                  <Typography.Text>@ </Typography.Text>{emailArray[1]}
                </Typography.Paragraph>}
              </span>
            </div>
          })}
        </div></div>
      }
    </div>
  </>
}

export default CreateBatch;
