import React from "react";
import { selectorService } from "../../services/selectorService";
import "antd/dist/antd.css";
import "./QuestionTable.css";
import parse from "html-react-parser";
import { Table, Space, Avatar, Menu, Dropdown, Drawer, Button, Checkbox, Radio, Pagination, Skeleton, Popconfirm, Empty, Typography, Tooltip, notification, message } from "antd";
import equal from "fast-deep-equal";
import Icon, { EyeOutlined, EyeFilled, StarOutlined, StarFilled, MinusOutlined, UserAddOutlined, UserDeleteOutlined, PlusOutlined, MoreOutlined,
  DeleteOutlined, EditOutlined, InfoCircleFilled } from "@ant-design/icons";
  import { uniqueId } from "lodash";
  import QuestionTypeLegend from "./QuestionTypeLegend";

import { ReactComponent as SubjectiveQuestionIcon } from '../assets/image/question-table-icons/sub-ques-icon.svg';
import { ReactComponent as MultipleResponseIcon } from '../assets/image/question-table-icons/mul-res-icon.svg';
import { ReactComponent as MultipleChoiceIcon } from '../assets/image/question-table-icons/mul-cho-icon.svg';
import { ReactComponent as TrueFalseIcon } from '../assets/image/question-table-icons/tru-fals-icon.svg';
import { ReactComponent as TranslateIcon } from '../assets/image/translate.svg';

import QuestionDrawer from "./QuestionDrawer";
import { Link } from "react-router-dom";

let subject = [];

let category = [];

let subcategory = [];

let type = [];

let complexity = [];

const data = [];

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

    this.state = {
      bottom: "bottomRight",
      classes: props.selectorState.classes,
      module_id: props.selectorState.category? props.selectorState.category : props.selectorState.subject,
      module: props.selectorState.category? 'category' : props.selectorState.subject? 'subject' : "",
      questionType: props.selectorState.questionType,
      complexity: props.selectorState.complexity,
      selectedRowKeys: [],
      data: [],
      map: {},
      visible: false,
      view: {},
      currentIndex: -1,
      result: {},
      page: 1,
      pageSize: 10,
      disabled: true,
      processing: false,
      pop: false,
      passRowData: -1
    };

    this.confirm = (
      <Popconfirm
        // disabled={this.state.disabled}
        title="Are"
        okText="Yes"
        cancelText="No"
        onCancel={() => {}}
        onConfirm={() => {}}
      ></Popconfirm>
    );

    this.columns = [
      {
        title: () => {
          return (
            <>
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item
                      key="attach-topic"
                      disabled={
                        this.state.selectedRowKeys.length > 0 ? false : true
                      }
                      onClick={this.attachSubCategory.bind(this)}
                    >
                      <span>
                        <PlusOutlined style={{ padding: "3px" }} />
                        Attach Subcategory
                      </span>
                    </Menu.Item>
                    <Menu.Item
                      key="detach-topic"
                      disabled={
                        this.state.selectedRowKeys.length > 0 ? false : true
                      }
                      onClick={this.detachSubCategory.bind(this)}
                    >
                      <span>
                        <MinusOutlined style={{ padding: "3px" }} />
                        Detach Subcategory
                      </span>
                    </Menu.Item>
                    <Menu.Item
                      key="delete-entry"
                      disabled={
                        this.state.selectedRowKeys.length > 0 ? false : true
                      }
                      onClick={() => this.deleteSelectedQuestions()}
                    >
                      <DeleteOutlined style={{ padding: "3px" }} />
                      Delete
                      {this.state.pop ? this.confirm : null}
                    </Menu.Item>
                  </Menu>
                }
                trigger={["click"]}
              >
                <a
                  className="ant-dropdown-link"
                  href="#"
                  onClick={(e) => e.preventDefault()}
                >
                  <Typography.Text strong>Actions</Typography.Text> <MoreOutlined />
                </a>
              </Dropdown>
            </>
          );
        },
        dataIndex: "isBookmarked edit key",
        key: "action",
        width: "100px",
        align: "center",
        render: (bookmarked, edit, key) => {
          if (!this.state.processing)
            return (
              <div>
                <span
                  style={{ display: "inline" }}
                  onClick={this.onChangeBookMark.bind(this, edit)}
                  hidden={window.location.pathname === "/bookmarkQuestions"}
                >
                  <StarOutlined
                    style={{ padding: "3px" }}
                    hidden={edit.isBookmarked}
                  />
                  <StarFilled
                    style={{ padding: "3px", color: "#FADB14" }}
                    hidden={!edit.isBookmarked}
                  />
                </span>{" "}
                <EyeFilled
                  style={{ padding: "3px" }}
                  hidden={this.state.currentIndex !== edit.index}
                />{" "}
                <EyeOutlined
                  style={{ padding: "3px" }}
                  onClick={this.onView.bind(this, edit)}
                  hidden={this.state.currentIndex === edit.index}
                />
              </div>
            );
          else return <Skeleton.Button style={{width: '50px' }} active />;
        },
      },
      {
        title: () => (<><Typography.Text strong>All Questions</Typography.Text></>),
        dataIndex: "title",
        key: "title",
        render: (text) => {
          if (!this.state.processing)
            return (
              <a className="Anchor">
                <span
                  title={text}
                  style={{
                    overflow: "hidden",
                    whiteSpace: "nowrap",
                    maxWidth: "50ch",
                    display: "block",
                    textOverflow: "ellipsis",
                  }}
                >
                  <Typography.Text>{text}</Typography.Text>
                </span>
              </a>
            );
          else return <Skeleton.Input style={{ width: "300px" }} active />;
        },
      },
      {
        title: () => (<><Typography.Text strong>Topics</Typography.Text></>),
        dataIndex: "topic_name",
        key: "topic_name",
        width: '15%',
        render: (text) => {
          if (!this.state.processing)
            return (
              <a className="AnchorBlue">
                <span >{text}</span>
              </a>
            );
          else return <Skeleton.Input style={{ width: "200px" }} active />;
        },
      },
      {
        title: () => (
          <Tooltip title={QuestionTypeLegend} placement="bottom" key={uniqueId()}>
            <Typography.Text strong>
              Type
            </Typography.Text>
            <InfoCircleFilled style={{color: 'blue', fontSize: '0.9rem', marginLeft: '0.3rem'}} />
          </Tooltip>
        ),
        dataIndex: "type",
        key: "type",
        align: "center",
        width: '100px',
        render: (text) => {
          if (!this.state.processing)
            return (
              <Space size="middle">
                {text === "MCQ" && <MultipleChoiceIcon />}
                {text === "MRQ" && <MultipleResponseIcon />}
                {text === "TNF" && <TrueFalseIcon />}
                {text === "SUB" && <SubjectiveQuestionIcon />}
              </Space>
            );
          else return <Skeleton.Button active />;
        },
      },
      {
        title: () => (<><Typography.Text strong>Complexity</Typography.Text></>),
        dataIndex: "complexity",
        key: "complexity",
        width: '9%',
        render: (text) => {
          if (!this.state.processing)
            return (
              <a>
                <Avatar
                  hidden={text !== 1}
                  style={{
                    backgroundColor: "#55B2FF",
                    verticalAlign: "middle",
                  }}
                  size="small"
                >
                  {" "}
                  E
                </Avatar>
                <Avatar
                  hidden={text !== 2}
                  style={{
                    backgroundColor: "#52C41A",
                    verticalAlign: "middle",
                  }}
                  size="small"
                >
                  M
                </Avatar>
                <Avatar
                  hidden={text !== 3}
                  style={{
                    backgroundColor: "#F8515B",
                    verticalAlign: "middle",
                  }}
                  size="small"
                >
                  D
                </Avatar>
              </a>
            );
          else return <Skeleton.Button active />;
        },
      },
      {
        title: () => (<><Typography.Text strong>Translated Into -</Typography.Text></>),
        dataIndex: "translated",
        key: "translated",
        width: "145px",
        render: (_, record) => {
          const { translated } = record;
          if (!this.state.processing) {
            let langNameArr = [];
            for(let item of translated) {
              const o = this.props.language.find(lang => (lang.id === item));
              //check if 'o' is undefined or not. if its not, then push it into an array.
              o?.name && langNameArr.push(o.name);
            }
            return (
              <>
                <Tooltip title={langNameArr.join(', ')} placement="bottom" key={uniqueId()}>
                  <Typography.Text>
                    {translated.length}
                  </Typography.Text>
                  <InfoCircleFilled style={{color: 'blue', fontSize: '0.9rem', marginLeft: '0.3rem'}} />
                </Tooltip>
                <Tooltip title={"Translate this question"} placement="topRight" key={uniqueId()}>
                  <Button onClick={() => this.navigateToTranslate(record)} size="small" className="ml-6-0">
                    <Link to={{pathname: "/translateQuestion", state: record}}><Icon component={TranslateIcon} style={{fontSize: 15, color: "var(--font-color)"}} /> </Link>
                  </Button>
                </Tooltip>
               </>
            );
          }
        }
      },
    ];
    this.handleLoad = this.handleLoad.bind(this);
    this.onPreviousClick = this.onPreviousClick.bind(this);
    this.onNextClick = this.onNextClick.bind(this);
  }
  static getDerivedStateFromProps(props, state) {
    // console.log("getDerivedStateFromProps"+props);
    return {
      classes: props.selectorState.classes,
      module_id: props.selectorState.category? props.selectorState.category : props.selectorState.subject,
      module: props.selectorState.category? 'category' : props.selectorState.subject? 'subject' : "",
      questionType: props.selectorState.questionType,
      complexity: props.selectorState.complexity,
    };
  }

  navigateToTranslate = (recordData) => {
    console.log(recordData);
  }

  deleteSelectedQuestions = async () => {
    // console.log(this.state.selectedRowKeys);
    try {
      const response = await selectorService.deleteQuestions(this.state.selectedRowKeys);
      if(+response.status.code < 0) {
        throw "Couldn't delete the selected questions";
      }
      this.setState(prev => ({...prev, selectedRowKeys: [], processing: true}));
      this.handleLoad(this.state.page, this.state.pageSize);
      notification.success({
          message: "Deleted"
      });
    } catch (error) {
      notification.error({
          message: error
      });
    }
  }

  removeTags(str) {
    if (str === null || str === "") return "";
    else str = str.toString();
    return str.replace(/(<([^>]+)>)/gi, "");
  }
  onView(rowData) {
    this.setState(prev => ({...prev, currentIndex: rowData.index, passRowData: rowData}));
    this.showDrawer();
  }

  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onChangeBookMark(rowData, context) {
    let questionArray = [];
    questionArray.push(rowData.key);
    let updatedValue = !rowData.isBookmarked;
    let data = [...this.state.data];
    data[rowData.index].isBookmarked = updatedValue;
    this.setState({ data: data }, () => {
      selectorService
        .updateBookMark(questionArray, updatedValue)
        .then((res) => {
          // console.log(res);
          if (res.status.code !== "1") {
            data = [...this.state.data];
            data[rowData.index].isBookmarked = !updatedValue;
            this.setState({ data: data });
          }
          // console.log("updated");
          // this.setState({processing:true})
          // this.handleLoad();
        });
    });

    // console.log(context+"  Bookmark Question =:");
  }

  updateBulkBookMark(value) {
    selectorService
      .updateBookMark(this.state.selectedRowKeys, value)
      .then((data) => {
        // console.log("updated");
        this.state.selectedRowKeys = [];
        this.setState({ processing: true });
        this.handleLoad(this.state.page);
      });
  }

  attachSubCategory() {}

  detachSubCategory() {}

  editQuestions() {}

  onPreviousClick() {
    let index = this.state.currentIndex;
    if (index == 0) return;
    let prevIndex = index - 1;
    let c = this.state.data[prevIndex];

    this.onView(c);
  }

  handleCancel = (e) => {
    // console.log(e);
    this.setState({
      visible: false,
      currentIndex: -1,
    });
  };

  onNextClick() {
    let index = this.state.currentIndex;
    let size = this.state.data.length;
    if (index >= size) return;
    let nextIndex = index + 1;
    let c = this.state.data[nextIndex];

    this.onView(c);
  }

  deleteQuestions(value) {
    selectorService
      .deleteQuestions(this.state.selectedRowKeys, value)
      .then((data) => {
        // console.log("updated");
        this.state.selectedRowKeys = [];
        this.setState({ processing: true });
        this.handleLoad(this.state.page, this.state.pageSize);
      });
  }

  attachTag() {}

  detachTag() {}

  componentDidUpdate(prevProps) {
    if (!equal(this.props.selectorState, prevProps.selectorState)) {
      // Check if it's a new user, you can also use some unique property, like the ID  (this.props.user.id !== prevProps.user.id)
      this.setState({ processing: true });
      this.handleLoad();
    }
  }
  componentDidMount() {
    window.addEventListener("load", this.handleLoad);
    this.setState({ processing: true });
    this.handleLoad();
  }

  componentWillUnmount() {
    window.removeEventListener("load", this.handleLoad);
  }

  handleLoad(page = 1, pageSize = 10) {
    //event.preventDefault();
    let jsonObj = {};
    jsonObj.classes = this.state.classes;
    if (this.state.complexity !== "")
      jsonObj.complexity = this.state.complexity;
    if (this.state.module_id !== "") jsonObj.module_id = this.state.module_id;
    if (this.state.module !== "") jsonObj.module = this.state.module;
    if (this.state.questionType !== "") jsonObj.type = this.state.questionType;
    jsonObj.page = page;
    jsonObj.pageSize = this.state.pageSize;
    jsonObj.translationMissing = this.props.selectorState.translationMissing;
    if (window.location.pathname === "/myQuestions") jsonObj.authorId = this.props.selectorState.currentUser.id;
    // console.log('jsonObj:', jsonObj);
    window.location.pathname !== "/bookmarkQuestions"
      ? selectorService.loadQuestions(jsonObj).then((data1) => {
          // console.log('Success:', data1);
          //data = $.parseJSON(data);
          if(+data1.status.code < 0) {
            throw data1.status.message[0];
          }
          let result = {};
          if (data1 !== undefined) result = data1.result;
          // this.state.data = [];
          if(result.total_pages > 1 && result.questions.length < 1) {
            this.handleLoad(this.state.page - 1, this.state.pageSize);
            return;
          }
          let data = [];
          let map = {};
          if (result.questions !== undefined) {
            for (let index = 0; index < result.questions.length; index++) {
              // console.log((result.questions[index]).title);
              let c = {};
              c.index = index;
              c.title = result.questions[index].title;
              c.key = result.questions[index].id;
              c.type = result.questions[index].type;
              c.type_name = result.questions[index].type_name;
              c.complexity = result.questions[index].complexity_code;
              c.translated = result.questions[index].languages_available;
              c.author = result.questions[index].author;
              c.isActive = result.questions[index].isActive;
              c.isBookmarked = result.questions[index].isBookmarked;
              c.source = result.questions[index].source;
              c.status = result.questions[index].status;
              c.topic_id = result.questions[index].topic_id;
              c.topic_name = result.questions[index].topic_name;
              c.edit = false;
              data.push(c);
              map[c.key] = c;
              //this.state.data.push(c);
            }
          }
          this.setState({
            page,
            pageSize,
            data: data,
            map: map,
            result: result,
            selectedRowKeys: [],
            processing: false,
          });
        }).catch(err => {
          console.log(err);
          notification.error("Something went wrong, please try reloading the page");
        })
      : selectorService.loadQuestionsBookmark(jsonObj).then((data1) => {
          // console.log('Success:', data1);
          //data = $.parseJSON(data);
          if(+data1.status.code < 0) {
            throw data1.status.message[0];
          }
          let result = {};
          if (data1 !== undefined) result = data1.result;
          // this.state.data = [];
          if(result.total_pages > 1 && result.questions.length < 1) {
            this.handleLoad(this.state.page - 1, this.state.pageSize);
            return;
          }
          let data = [];
          let map = {};
          if (result.questions !== undefined) {
            for (let index = 0; index < result.questions.length; index++) {
              // console.log((result.questions[index]).title);
              let c = {};
              c.index = index;
              c.title = result.questions[index].title;
              c.key = result.questions[index].id;
              c.type = result.questions[index].type;
              c.type_name = result.questions[index].type_name;
              c.translated = result.questions[index].languages_available;
              c.complexity = result.questions[index].complexity_code;
              c.author = result.questions[index].author;
              c.isActive = result.questions[index].isActive;
              c.isBookmarked = result.questions[index].isBookmarked;
              c.source = result.questions[index].source;
              c.status = result.questions[index].status;
              c.topic_id = result.questions[index].topic_id;
              c.topic_name = result.questions[index].topic_name;
              c.edit = false;
              data.push(c);
              map[c.key] = c;
              //this.state.data.push(c);
            }
          }
          this.setState({
            page,
            pageSize,
            data: data,
            map: map,
            result: result,
            selectedRowKeys: [],
            processing: false,
          });
        }).catch(err => {
          console.log(err);
          notification.error("Something went wrong, please try reloading the page");
        });
    //console.log(data);
  }

  onSelectChange = (selectedRowKeys) => {
    // console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  render() {
    const { selectedRowKeys } = this.state;
    // console.log(this.state.data); // logs all the question fetched 
    // console.log(selectedRowKeys)
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      selections: [
        Table.SELECTION_ALL,
        Table.SELECTION_INVERT,
        {
          key: "odd",
          text: "Select Odd Row",
          onSelect: (changableRowKeys) => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            this.onSelectChange(newSelectedRowKeys);
            // this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
        {
          key: "even",
          text: "Select Even Row",
          onSelect: (changableRowKeys) => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            this.onSelectChange(newSelectedRowKeys);
            // this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
      ],
    };
    let data = [...this.state.data];
    data = data.map((x) => {
      x = { ...x };
      x.title = this.removeTags(x.title);
      return x;
    });

    if(this.state.processing) {
      let dataSke = [];
      for (let i = 0; i < this.state.pageSize; i++) {
        let y = {};
        y.key = uniqueId();
        y.title = <Skeleton.Input style={{ width: "300px" }} />;
        y.topic_name = <Skeleton.Input style={{ width: "200px" }} />;
        y.complexity = 4;
        y.type = <Skeleton.Input style={{ width: "100px" }} />;
        dataSke.push(y);
      }
      // console.log(dataSke);
      return (
        <>
          <Table
            columns={this.columns}
            dataSource={dataSke}
            rowSelection={rowSelection}
          />
        </>
      );
    }

    if (!this.state.processing) {
      return (
        <div>
          <Table
            // {...this.state}
            // rowKey="key"
            // loading={this.state.processing}
            showHeader={true}
            rowSelection={rowSelection}
            columns={this.columns}
            bordered
            pagination={false}
            dataSource={data}
            scroll={{
              x: 1100
            }}
          />
          <Pagination
            className="pagination-row"
            current={this.state.page}
            pageSize={this.state.pageSize||10}
            defaultPageSize={10}
            showSizeChanger={true}
            defaultCurrent={1}
            total={this.state.result.total_count}
            onChange={(page, pageSize) => {
              this.setState({ page, pageSize, processing: true }, () => {
                this.handleLoad(page, pageSize);
              });
            }}
          />
          {this.state.visible && <QuestionDrawer number={this.state.currentIndex + 1 + 10*(this.state.page-1)}
            handleNextButton={this.onNextClick} disableNext={this.state.currentIndex === (this.state.data.length - 1)}
            handlePreviousButton={this.onPreviousClick} disablePrev={this.state.currentIndex === 0}
            language={this.props.language} visible={this.state.visible} 
            setVisible={() => this.setState(prev => ({...prev, visible: false, currentIndex: -1}))} 
            recordData={this.state.passRowData} 
          />}
        </div>
      );
    } 
  }
}

export default QuestionTableNew;
