import React from 'react';
import { selectorService } from '../../../services/selectorService';
// import 'antd/dist/antd.css';
import '../QuestionTable.css';
import { Link } from 'react-router-dom';
import { Table, Avatar, Menu, Dropdown, Pagination, Skeleton, Empty, Typography, notification } from 'antd';
import equal from 'fast-deep-equal';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { uniqueId } from 'lodash';
import DraftQuestDrawer from './DraftQuestDrawer';



let subject = [

];

let category = [

];

let subcategory = [

];

let type = [


];

let complexity = [


];

const data = [];

// const bottomOptions = [
//   { label: 'bottomLeft', value: 'bottomLeft' },
//   { label: 'bottomCenter', value: 'bottomCenter' },
//   { label: 'bottomRight', value: 'bottomRight' },
//   { label: 'none', value: 'none' },
// ];





class QuestionTable 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: false,
          processing: false,
          pop: false,
          passRowData: -1
        };

        

        this.columns = [

            // {
            //   dataIndex: 'isBookmarked edit key' ,
            //   key: 'action',
            //   width:'8%',
            //   render: (bookmarked, edit, key) => (
            //   <div>
            //   <span style={{display:'inline'}} onClick={this.onChangeBookMark.bind(this,edit)}><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>
            //   ),
            // },
            {
                title: () => <Typography.Text strong>Action</Typography.Text>,
                dataIndex: 'key',
                key: 'Edit',
                align: 'center',
                width: "250px",
                render: (key, rowState, _) => {
                    if (this.state.processing)
                        return (<Skeleton.Button active />)
                    else {
                        const menuEdit = (
                            <Menu onClick={(e) => this.menuClick(e, rowState)}>
                                <Menu.Item key="1">
                                    View
                                </Menu.Item>
                            </Menu>
                        );
                
                        const menuSubmit = (
                            <Menu onClick={(e) => this.menuClick(e, rowState)}>
                                <Menu.Item key="2" danger>
                                    Delete
                                </Menu.Item>
                            </Menu>
                        );
                        return (
                            <>
                                <div style={{display: 'flex', gap: 10, justifyContent: 'center'}}>
                                    <Dropdown.Button overlay={menuEdit} disabled={this.state.disabled}>
                                        <Link to={{
                                            className: 'AnchorBlue',
                                            pathname: "/addQuestion",
                                            state: key, rowState
                                        }}>
                                            <span>
                                                <EditOutlined style={{ padding: '3px' }} onClick={() => this.handleEdit(key, rowState)} />
                                                Edit
                                            </span>
                                        </Link>
                                    </Dropdown.Button>
                                    <Dropdown.Button type='primary' onClick={async () => { 
                                            this.setState(prev => ({...prev, disabled: true})); 
                                            const res = await selectorService.editQuestion(rowState.key, {id: rowState.key, status: "PUBLISHED"});
                                            // if(res) {
                                            //     this.setState(prev => ({...prev, disabled: false})); 
                                            // }
                                            this.handleLoad(this.state.page, this.state.pageSize);
                                        }} 
                                        disabled={this.state.disabled}
                                        overlay={menuSubmit}>
                                            Submit
                                    </Dropdown.Button>
                                </div>
                            </>
                        )
                    }
                }
            },
            {
                title: () => <Typography.Text strong>Draft Questions</Typography.Text>,
                dataIndex: 'title',
                key: 'title',
                render: text => {
                    if (this.state.processing)
                        return (<Skeleton.Button active />)
                    else return (
                        <a className='Anchor'>
                            <span title={text} 
                                style={{ overflow: 'hidden', whiteSpace: 'nowrap', 
                                maxWidth: '50ch', display: 'block', fontWeight: 'normal', padding: '0px', 
                                textOverflow: 'ellipsis' 
                                }}
                            ><Typography.Text>{text}</Typography.Text></span>
                        </a>
                    )
                }
            },
            { 
              title: () => <Typography.Text strong>Topic</Typography.Text>,
              dataIndex: 'topic_name',
              key: 'topic_name',
              width: "12%",
              render: text => {
                if (this.state.processing)
                    return (<Skeleton.Button active />)
                else return (
                    <a className='AnchorBlue'><span style={{ fontWeight: 'normal' }}>{text}</span></a>
                )
              }
            },
            // { 
            //   title:'Sub Topic',
            //   dataIndex: 'subtopic_name',
            //   key: 'subtopic_name',
            //   render: text => <a className='AnchorBlue'><span style={{ fontWeight: 'normal' }}>{text}</span></a>
            // },

            {
                title: () => <Typography.Text strong>Complexity</Typography.Text>,
                dataIndex: 'complexity',
                align: 'center',
                key: 'complexity',
                width: "8%",
                render: complexity => {
                    if (this.state.processing)
                        return (<Skeleton.Button active />)
                    else {
                        if (complexity !== 4)
                            return (<a>
                                {complexity === 1 ?
                                    <Avatar
                                        // hidden={text!==1} 
                                        style={{ backgroundColor: '#55B2FF', verticalAlign: 'middle' }} size="small" complexity={complexity}> E
    
                                    </Avatar> : ""}
                                {complexity === 2 ?
                                    <Avatar
                                        // hidden={text!==2} 
                                        complexity={complexity} style={{ backgroundColor: '#52C41A', verticalAlign: 'middle' }} size="small" >M
    
                                    </Avatar> : ""}
                                {complexity === 3 ?
                                    <Avatar complexity={complexity}
                                        // hidden={text!==3}
                                        style={{ backgroundColor: '#F8515B', verticalAlign: 'middle' }} size="small" >D
    
                                    </Avatar> : ""}
                            </a>)
                        else return (<Skeleton.Button active />)
                    }
                }
            },
        ];
        this.handleLoad = this.handleLoad.bind(this);
        this.onPreviousClick = this.onPreviousClick.bind(this);
        this.onNextClick = this.onNextClick.bind(this);
        this.handleEdit = this.handleEdit.bind(this);
        this.menuClick = this.menuClick.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
        };
    }

    menuClick =  async (e, record) => {
        if(e.key === "1") {
            this.setState(prev => ({...prev, visible: true}));
            this.onView(record);
        }
        if(e.key === "2") {
            try {
                const response = await selectorService.deleteQuestions([record.key]);
                notification.success({
                    message: "Deleted"
                });
                this.handleLoad(this.state.page, this.state.pageSize);
            } catch (error) {
                notification.error({
                    message: "Something went wrong"
                });
            }
        }
    }

    onView = (rowData) => {
        this.setState(prev => ({...prev, currentIndex: rowData.index, passRowData: rowData}));
        this.showDrawer();
    }

    handleEdit = (id) => {
        this.setState({
            que_id: id
        })

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


    onChangeBookMark(rowData, context) {
        let questionArray = [];
        questionArray.push(rowData.key);
        let updatedValue = !rowData.isBookmarked;
        selectorService.updateBookMark(questionArray, updatedValue).then(data => {
            rowData.isBookmarked = updatedValue;
            // 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();
        });

    }

    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 >= this.state.data)
            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();
        });
    }

    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)
        {
            // console.log('here');
            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;
        if (this.props.selectorState.translationMissing)
            jsonObj.translationMissing = this.props.selectorState.translationMissing;
        // console.log('jsonObj:', jsonObj);
        jsonObj.page = page;
        jsonObj.pageSize = pageSize;
        selectorService.draftQuestion(jsonObj).then(data1 => {
            // console.log('Success:', data1);
            // console.log('Success:', data1.result.questions.id);

            //  this.setState({
            //   id:data1.result.questions.id
            // })
            //data = $.parseJSON(data);
            let result = {};
            if (data1 !== undefined)
                result = data1.result;

            //check if current page has exhausted all its questions list
            let skipAssign = false;
            if(page > result.total_pages) {
                skipAssign = true;
                this.handleLoad((page - 1), pageSize);
            }
            this.state.data = [];
            let data = [];
            let map = {};
            if (result.questions !== undefined && !skipAssign) {

                for (let index = 0; index < result.questions.length; index++) {
                    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.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.subtopic_id = (result.questions[index]).subtopic_id;
                    c.subtopic_name = (result.questions[index]).subtopic_name;
                    c.options = (result.questions[index]).options
                    c.edit = false;
                    data.push(c);
                    map[c.key] = c;
                    //this.state.data.push(c);
                }
            }
            !skipAssign && this.setState({
                page,
                pageSize,
                data: data,
                map: map,
                result: result,
                processing: false
            });
            this.setState(prev => ({...prev, disabled: false})); 
        });
        //console.log(data);
    }


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

    removeTags(str) {
        if (str === null || str === "") return "";
        else str = str.toString();
        return str.replace(/(<([^>]+)>)/gi, "");
    }



    render() {
        const { selectedRowKeys } = this.state;
        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.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.setState({ selectedRowKeys: newSelectedRowKeys });
                    },
                },
            ],
        };

        let data = [...this.state.data];
        data = data.map((x) => {
            x = { ...x };
            x.title = this.removeTags(x.title);
            return x;
        });
        // console.log(data);
        if (data.length !== 0)
            return (
                <div>

                    <Table {...this.state}
                        rowKey='key' 
                        // rowSelection={rowSelection}
                        columns={this.columns}
                        bordered
                        pagination={false}
                        dataSource={data}
                        scroll={{
                            x: 1200
                        }
                        }
                    />
                    <Pagination defaultPageSize={10}
                        current={this.state.page}
                        pageSize={this.state.pageSize||10} 
                        style={{ float: 'right' }} 
                        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 && <DraftQuestDrawer number={this.state.currentIndex + 1 + 10*(this.state.page - 1)} 
                        language={this.props.language} visible={this.state.visible} 
                        setVisible={() => this.setState(prev => ({...prev, visible: false, currentIndex: -1}))} 
                        recordData={this.state.passRowData}
                    />}
                </div>
            )
        else 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.Edit = [];
                dataSke.push(y);
            }
            return (
                <>
                    <Table
                        columns={this.columns}
                        dataSource={dataSke}
                        // rowSelection={rowSelection}
                    />

                </>
            )
        }
        else return (<Empty />);
    };
};

export default QuestionTable;
