import React from "react";
import "../CreateExamName.css";
import {
  Input,
  Button,
  Form,
  message,
  Upload,
  Space,
  Dropdown,
  Menu,
  Typography,
} from "antd";
import { UploadOutlined, DownOutlined } from "@ant-design/icons";
import { authenticationService } from "../../../_services";
import { selectorService } from "../../../services/selectorService";
import { t } from "i18next";
import empty from "../../EmptyImage";
import { Trans } from "react-i18next";

const primaryblue = "#3b3cea";

class CreateExamName extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentUser: authenticationService.currentUserValue,
      examName: props.selectorState.name,
      image: empty(),
      update: false,
      examId: "",
      options: [],
      type: "",
      buttons: [],
      topicName: "",
      selected: {},
    };
    this.handleCreateExamName = this.handleCreateExamName.bind(this);
    this.onTextChange = this.onTextChange.bind(this);
    this.sendData = this.sendData.bind(this);
  }
  onTextChange = (event) => {
    this.setState({
      examName: event.target.value,
      update: true,
    });
  };

  handleSubjectButtonClick(index) {
    // console.log("herre");
    let tempSubjects = [...this.state.buttons];
    tempSubjects[index].buttonState = true;
    tempSubjects = tempSubjects.map((x, idx) => {
      if (idx === index) {
        x.buttonState = true;
        return x;
      }
      x.buttonState = false;
      return x;
    });
    let selected = tempSubjects[index];
    // console.log(selected);
    // let array = this.state.subjects.filter((x) => x.buttonState);
    this.setState({ buttons: tempSubjects, selected });
    // this.forceUpdate();
  }

  handleCreateExamName() {
    if (!this.state.examName || this.state.examName === "") {
      message.warning("Please enter a valid practise name");
    } else if (this.state.selected.id === undefined) {
      message.warning("Please select a subject or topic");
    } else {
      if (!this.state.update)
        this.state.examName = this.props.selectorState.name;
      let json = {
        name: this.state.examName,
        image: this.state.image,
        module: this.state.type === "Subjects" ? "Subject" : "Category",
        module_id: this.state.selected.id,
      };
      message.loading({ content: "Creating Practise Name..." });
      selectorService.createPractise(json).then((data) => {
        console.log(data);
        if (!data) {
          message.warning("Some error occured");
        } else {
          let result = data.result;
          result.current = 1;
          result.image = this.state.image;
          message.success({ content: "Practise Name Created!", duration: 3 });
          this.sendData(result);
        }
      });
    }
  }
  sendData = (result) => {
    this.props.parentCallback(result);
  };

  render() {
    // console.log(this.state.buttons);
    return (
      <>
      <div className="createExamName">
        {/* <Form className="exam-form"> */}
          <Typography.Text strong style={{ color: "var(--font-color-primary)" }}>
            <Trans i18nKey={"practice.step1.practiceName"}>Practice Name</Trans>
          </Typography.Text>
          {/* <br /> */}
          {/* <Space> */}
            <Input
              style={{width: 250}}
              placeholder="Enter Practise Name"
              value={this.state.examName}
              onChange={(e) => {
                this.onTextChange(e);
              }}
            />
            {/* <Upload>
              <Button type="primary" icon={<UploadOutlined />}>
                Upload
              </Button>
            </Upload> */}
          {/* </Space> */}
          {/* <br />
          <br /> */}
          <Typography.Text strong style={{ color: "var(--font-color-primary)" }}>
            <Trans i18nKey={"practice.step1.pracType"}>Practice Type</Trans>
          </Typography.Text>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item
                  onClick={() => {
                    // console.log("Subjects");
                    selectorService
                      .loadSubjects()
                      .then((res) => {
                        // console.log("inside", res);
                        this.setState({
                          options: isNaN(parseInt(res.result.length))
                            ? []
                            : res.result,
                          type: "Subjects",
                          buttons: isNaN(parseInt(res.result.length))
                            ? []
                            : res.result,
                        });
                      })
                      .catch((err) => console.log(err));
                  }}
                  key="0"
                >
                  <Trans i18nKey={"subjects"}>Subjects</Trans>
                </Menu.Item>
                <Menu.Item
                  onClick={(e) => {
                    // console.log("Topics");
                    selectorService.loadSubjects().then((res) => {
                        // console.log(res);
                        this.setState({
                          options: isNaN(parseInt(res.result.length))
                            ? []
                            : res.result,
                          type: "Topics",
                          buttons: [],
                          selected: {},
                        });
                      })
                      .catch((err) => console.log(err));
                  }}
                  key="1"
                >
                  <Trans i18nKey={'topics'}>Topics</Trans>
                </Menu.Item>
              </Menu>
            }
            trigger={["click"]}
          >
            <a
              className="custom-dropdown-link"
              onClick={(e) => e.preventDefault()}
              href="#"
            >
              {this.state.type === "" ? (
                <>
                  <Typography.Text><Trans i18nKey={"practice.step1.choose"}>Choose here</Trans></Typography.Text> <DownOutlined />
                </>
              ) : (
                <><Typography.Text>{this.state.type}</Typography.Text> <DownOutlined /></>
              )}
            </a>
          </Dropdown>


          {this.state.type !== "Topics" ? (
            <></>
          ) : (
            <>
              {/* <br />
              <br /> */}
              <Typography.Text strong style={{ color: "var(--font-color-primary)" }}>
                <Trans i18nKey={"topics"}>Topics</Trans>
              </Typography.Text>
              <Dropdown
                overlay={
                  <Menu>
                    {this.state.options.map((x, idx) => {
                      return (
                        <Menu.Item
                          onClick={(e) => {
                            // console.log("Topic");
                            selectorService
                              .loadCategory(x.id)
                              .then((res) => {
                                this.setState({
                                  buttons: res.result,
                                  topicName: x.name,
                                });
                              })
                              .catch((err) => console.log(err));
                          }}
                          key={idx}
                        >
                          {x.name}
                        </Menu.Item>
                      );
                    })}
                  </Menu>
                }
                trigger={["click"]}
              >
                <a
                  className="custom-dropdown-link"
                  onClick={(e) => e.preventDefault()}
                  href="#"
                >
                  {this.state.topicName === "" ? (
                    <>
                      <Typography.Text>
                        <Trans i18nKey={"practice.step1.choose"}></Trans>
                      </Typography.Text> <DownOutlined />
                    </>
                  ) : (
                    <><Typography.Text>{this.state.topicName}</Typography.Text> <DownOutlined /></>
                  )}
                </a>
              </Dropdown>
            </>
          )}
          {this.state.buttons.length === 0 ? (
            <></>
          ) : (
            <>
              {/* <br /> */}
              {this.state.type !== "Topics" 
                ? (<Typography.Text strong style={{ color: "var(--font-color-primary)" }}><Trans i18nKey={"selectSub"}>Select Subjects</Trans></Typography.Text>) 
                : (<Typography.Text strong style={{ color: "var(--font-color-primary)" }}>{t('practice.step1.selectTopics')}
                    <Trans i18nKey={"practice.step1.select"}>Select Topics</Trans>
                  </Typography.Text>)}
              <Space wrap size={[8, 0]}>
                {this.state.buttons.map((subject, index) => {
                  return (
                    <Button
                      onClick={() => this.handleSubjectButtonClick(index)}
                      className={
                        subject.buttonState
                          ? "subjectButtonTrue"
                          : "subjectButtonFalse"
                      }
                      // style={{
                      //   color: subject.buttonState ? "#1890FF" : "#cccccc",
                      //   borderColor: subject.buttonState
                      //     ? "#1890FF"
                      //     : "#cccccc",
                      // }}
                      key={index}
                      title={subject.name}
                    >
                      {subject.name}
                    </Button>
                  );
                })}
              </Space>
            </>
          )}
          {/* <br /> */}
        {/* </Form> */}
      </div>
      <div className="button-container" data-need-margin={"false"}>
        <Button
          type="primary"
          onClick={(e) => {
            // console.log("inside");
            this.handleCreateExamName();
          }}
        >
          <Trans i18nKey={"continue-btn"}>Continue</Trans>
        </Button>
      </div>
      </>
    );
  }
}

export default CreateExamName;
