import React from "react";
import "./SelectSubjects.css";
import { Button, Form, Switch, Drawer, Input, message, Typography, Modal, Steps } from "antd";
import {
  FormOutlined,
  CheckSquareTwoTone,
  CloseSquareTwoTone,
  InfoCircleOutlined,
} from "@ant-design/icons";
import { authenticationService } from "../../_services";
import { selectorService } from "../../services/selectorService";
import DragDropContainer from "./DragNDrop/Container";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import AddQuestions from "./AddQuestions";
import { isEqual } from "lodash";
import empty from "../EmptyImage";
import { withTranslation, Trans } from 'react-i18next';

let subject = [];

class ArrangeSections extends React.Component {
  constructor(props) {
    super(props);
    this.child = React.createRef();
    this.state = {
      currentUser: authenticationService.currentUserValue,
      examName: props.selectorState.name,
      update: false,
      examId: props.selectorState.examId,
      sections: props.selectorState.sections,
      currentUser: authenticationService.currentUserValue,
      authorId: props.selectorState.authorId,
      examStatus: props.selectorState.examStatus,
      examTypeId: props.selectorState.examTypeId,
      id: props.selectorState.id,
      image: props.selectorState.image,
      instituteId: props.selectorState.instituteId,
      isActive: props.selectorState.isActive,
      languageId: props.selectorState.languageId,
      subjects: [],
      currentStatus: 0,
      rearrange: true,
      visible: false,
      visibleButtonIndex: 0,
      modal: { examId: props.selectorState.id },
      classes: 1,
      loaded: false,
      updated: false,
      updatedName: props.selectorState.name,
      currentStep: 0
    };

    this.steps = [
      {
        title: this.props.t('step-1'),
        description: this.props.t('attach-que'),
        // content: <AddQuestions selectorState={state} parentCallback={callbackFunctionStep1} />,
      },
      {
        title: this.props.t('step-2'),
        description: this.props.t('review-btn'),
        // content: <ReviewQuestions />
      }
    ]

    this.addImageDefault = () => {
      this.setState (prev => {
        return { ...prev, image: empty() }
      });
    }

    this.sendData = this.sendData.bind(this);
    this.handleRearrange = this.handleRearrange.bind(this);
    this.handleArrangeSubject = this.handleArrangeSubject.bind(this);
    this.handleLoadSections = this.handleLoadSections.bind(this);
  }

  componentDidMount() {
    this.handleLoadSections();
  }

  componentDidUpdate(prevprops, prevState) {
    // console.log("Previous :", prevState);
    if (!this.state.updated)
      selectorService.loadSections(this.state.id).then((data) => {
        // console.log("Success:", data);
        if (data) {
          const result = data.result;
          // this.state.sections = [];
          let array = [];
        const sections = prevState.sections; // prevState.sections because we want to preserve the new order of the re-arranged section
          for (let index = 0; index < sections.length; index++) {
            let c = {};
            // c.id = sections[index].id;
            // c.label = sections[index].subject_name;
            // c.value = sections[index].subject_id;
            // c.section_state = sections[index].section_state;
            // c.totalQuestion = sections[index].total_questions;
            // c.subject_id = sections[index].subject_id;
            // c.index = index;
            // c.buttonState = false;
            const correspondingSection = result.sections.find(subject => subject.subject_id === sections[index].subject_id);
            if(correspondingSection) {
              c.id = correspondingSection.id;
              c.label = correspondingSection.subject_name;
              c.value = correspondingSection.subject_id;
              c.section_state = correspondingSection.section_state;
              c.totalQuestion = correspondingSection.total_questions;
              c.subject_id = correspondingSection.subject_id;
              c.index = index;
              c.buttonState = false;
            }
            array.push(c);
          }
          // console.log(array, this.state.sections, isEqual(array, this.state.sections));
          if (!isEqual(array, this.state.sections)) {
            this.setState({ sections: array, updated: true });
          }
        }
      });
  }

  handleLoadSections = () => {
    selectorService.loadSections(this.state.id).then((data) => {
      // console.log("Success:", data);
      const result = data.result;
      this.state.sections = [];
      const sections = result.sections;
      for (let index = 0; index < sections.length; index++) {
        let c = {};
        c.id = sections[index].id;
        c.label = sections[index].subject_name;
        c.value = sections[index].subject_id;
        c.section_state = sections[index].section_state;
        c.totalQuestion = sections[index].total_questions;
        c.subject_id = sections[index].subject_id;
        c.index = index;
        c.buttonState = false;
        this.state.sections.push(c);
      }
      this.state.loaded = true;
      this.forceUpdate();
    });
  };

  handleRearrange = (event) => {
    this.setState({
      rearrange: event,
    });
  };

  callbackFunctionDragNDrop = (childData) => {
    // console.log("Parent recieved Selector Data: " + JSON.stringify(childData));
    this.setState({
      sections: childData,
      updated: true,
    });
  };

  callbackButtonClick = (childData) => {
    // console.log("Parent recieved Selector Data: " + childData);

    this.setState({
      visible: true,
      visibleButtonIndex: childData,
      modal: {
        sections: this.state.sections,
        visible: true,
        examId: this.props.selectorState.id,
        classes: 1,
        module_id: this.state.sections[childData].value,
        module: "subject",
        subjectId: this.state.sections[childData].subject_id,
        sectionName: this.state.sections[childData].label,
      },
      subject: this.state.sections[childData].label,
    });
  };

  handleArrangeSubject() {
    if ( this.state.sections.filter((x) => x.section_state === "PUBLISHED").length !== this.state.sections.length ) {
      message.warning("Please add questions for all sections");
    } else {
      let sectionsId = [];
      this.state.sections.forEach((section) => {
        sectionsId.push(section.id);
      });
      let json = {};
      json.idList = sectionsId;
      selectorService.arrangeSectionsFromExam(this.state.id, json)
        .then((data) => {
          if(+data.status.code < 0) {
            throw data.status.message[0];
          }
          let result = {};
          result.current = 3;
          result.sections = this.state.sections;
          result.rearrange = this.state.rearrange;
          result.exam = this.state.examName;
          this.sendData(result);
        }).catch(err => {
          message.error("Something went wrong, could not continue to next step.");
          console.log(err);
        });
    }
  }

  sendData = (result) => {
    // console.log(result);
    this.props.parentCallback(result);
  };

  handleCancel = (e) => {
    // console.log(e);
    // this.state.modal.visible = false;
    this.setState(prev => ({
      ...prev,
      visible: false,
      updated: false,
      currentStep: 0
    }));
  }

  render() {
    const { current } = this.state.currentStatus;
    // let disabledSize = this.state.sections.filter((x) => x.section_state === "PUBLISHED").length !== this.state.sections.length;
    // console.log(disabledSize, this.state.sections);
    return (
      <div className="SelectSubjects SelectSubjects--Exam">
        <DndProvider backend={HTML5Backend}>
        <Form className="exam-form">
          <div className="exam">
            <table className="examTable">
              <tbody>
                <tr>
                  <td>
                    <div className="examNameOuter">
                      <div>
                        <img
                          onError={this.addImageDefault}
                          width={100}
                          height={100}
                          src={this.state.image}
                        ></img>
                      </div>

                      <div className="examName">
                        <div>
                          <Typography.Text style={{color: 'var(--font-color-primary)', fontSize: '0.85rem'}}>{this.props.t('exam-name')}</Typography.Text>
                        </div>
                        <div>
                          <span
                            hidden={this.state.editing}
                            className="examNameSpan"
                          >
                            {this.state.examName}
                          </span>
                          <span>
                            {" "}
                            <Input
                              value={this.state.updatedName}
                              onChange={(e) =>
                                this.setState({ updatedName: e.target.value })
                              }
                              hidden={!this.state.editing}
                              style={{ width: "60%" }}
                              placeholder="Exam Name"
                            />{" "}
                          </span>
                        </div>
                      </div>
                    </div>
                  </td>
                  <td
                    className="examNameEdit"
                    style={{ cursor: "pointer", width: "5px" }}
                  >
                    <div onClick={() => this.setState({ editing: true })}>
                      <FormOutlined hidden={this.state.editing} style={{ fontSize: "16px", color: "#1890FF" }} twoToneColor="#1890FF" />
                    </div>
                    <div hidden={!this.state.editing} onClick={() => {
                        this.setState({
                          editing: false,
                          updatedName: this.state.examName,
                        });
                      }}
                    >
                      <CloseSquareTwoTone />
                    </div>
                    <div onClick={() => {
                        const { examId, updatedName, image, authorId, examTypeId, id, } = this.state;
                        selectorService.updateExam({ id, examId, name: updatedName, image, authorId, examTypeId, })
                          .then((res) => {
                            // console.log(res);
                          })
                          .catch((err) => {
                            console.log(err);
                          });
                        this.setState({
                          editing: false,
                          examName: this.state.updatedName,
                        });
                      }}
                      hidden={!this.state.editing}
                    >
                      <CheckSquareTwoTone />
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>{" "}
          </div>

          <br />
          <div className="select-subject-grid">
          <div className="subject__switching">
            <Typography.Text strong 
              style={{color: 'var(--font-color-primary)', display: 'block', alignSelf: 'start', maxWidth: 120}}>
                {this.props.t('add-que-sub')}
            </Typography.Text>
          </div>
          {this.state.loaded && !this.state.visible ? (
            // <div className="subjectButtons">

                <DragDropContainer key={"container-movable"} id={this.state.id} modelState={this.state.sections} 
                parentCallback={this.callbackFunctionDragNDrop} parentButtonCallback={this.callbackButtonClick}/>
  
            // </div>
          ) : null}
          <br />
          <div>
            <span>
            <InfoCircleOutlined />{" "}
              <strong style={{color: 'orange'}}>{this.props.t('note')}: </strong>
              <Trans i18nKey="step-3-note-main">
                <strong>CLICK</strong> on each subject to add their respective questions.
              </Trans>
            </span>
            <p>
              <Trans i18nKey="step-3-note-2">
                You can also <strong>DRAG</strong> the subjects to reorder them
              </Trans>
            </p>
          </div>
          </div>
          <br />
          <div className="button-container" data-need-margin={"false"}>
            <Button type="primary" onClick={(e) => { this.handleArrangeSubject(); }} >
              {this.props.t('continue-btn')}
            </Button>
          </div>
        </Form>
        {this.state.visible && <Modal 
        title={
          <Steps current={this.state.currentStep}>
            {this.steps.map((item) => (
              <Steps.Step key={item.title} title={item.title} description={item.description} />
            ))}
          </Steps>
        }
        width={"auto"} 
        // placement="right" 
        centered
        closable={true} 
        wrapClassName={"attach-question--modal"}
        style={{
          minWidth: "360px",
          maxWidth: "calc(100vw - 40px)",
          maxHeight: "calc(100vh - 100px)"
        }}
        onCancel={this.handleCancel} 
        visible={this.state.visible} 
        destroyOnClose={true}
        footer={            
        <div>
          <Button
            onClick={this.state.currentStatus===0? () => this.handleCancel()
              : () => this.child.current.handleCancel()}
            type="primary"
            style={{ marginRight: 8 }}
          >
            {this.props.t('close-btn')}
          </Button>
          {this.state.currentStep === 0? <Button
              onClick={() => {
                this.child.current.reviewQuestions();
                this.setState(prev => ({...prev, currentStep: 1}));
              }}
              type="primary"
              style={{ marginRight: 8 }}
            >
              {this.props.t('review-btn')}
            </Button> 
          : <Button
              onClick={async () => {
                const a = await this.child.current.handleSubmit();
                // this.child.current.handleCancel();
                // check if a is NOT = 0, then set step back to 0.
                // if a = 0, then operation was unsuccessful, so the step remains at 1.
                // a !== 0 && this.setState(prev => ({...prev, currentStep: 0}));
              }}
              type="primary"
              // style={{ marginRight: 8 }}
            >
              {this.props.t('submit-btn')}
            </Button>
          }
        </div>}
        >
          <AddQuestions step={this.state.currentStep} ref={this.child} closeComplete={this.handleCancel} addQuestion={this.state.modal} />
          {/* </AddQuestions> */}
        </Modal>}
        </DndProvider>
      </div>
    );
  }
}

export default withTranslation()(ArrangeSections);
