import { Alert, Select, Space, Table, Tooltip } from 'antd';
import React, { useCallback } from 'react';
import { lowerCase } from 'lodash';
// import { selectorService } from '../../../services/selectorService';
import TopicOptionData from './TopicOptionData';
import ComplexityAvatar from './ComplexityAvatar';
import EditUploadedQuestion from './EditUploadedQuestion';

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 DeleteIcon } from '../../assets/image/question-table-icons/delete-icon.svg';
import { EyeOutlined, EyeFilled, SyncOutlined } from '@ant-design/icons';
import UseValidation from './UseValidation';

const errorStyle = {
    border: '#ff00002c 1px solid',
    backgroundColor: '#ff00001c'
}


const QuestionListTable = ({ data, setData, subjects, questionTypes, formNewOptionProperty }) => {

    const mounted = React.useRef(false);
    const [page, setPage] = React.useState({current: 0});

    const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
    const [tableDataLoading, setTableDataLoading] = React.useState(false);
    const [tableData, setTableData] = React.useState([]);
    const [expandedRows, setExpandedRows] = React.useState([]);

    // parse the subject received from context
    let parsedSubjects = useCallback(subjects.map((item) => {
        return ({ label: item.name, value: item.id, topicList: item.topics, code: item.id });
    }), [subjects]);

    // parse the question types received from context
    let parsedQueTypes = useCallback(questionTypes.map((item) => {
        if (item.code === "MRQ")
            return ({ label: <><MultipleResponseIcon /> <div className='option--text'>Multiple Response Question</div></>, value: item.code });
        if (item.code === "MCQ")
            return ({ label: <><MultipleChoiceIcon /> <div className='option--text'>Multiple Choice Question</div></>, value: item.code });
        if (item.code === "TNF")
            return ({ label: <><TrueFalseIcon /> <div className='option--text'>True and False Question</div></>, value: item.code });
    }), [questionTypes]);



    // parse the category/topic received from server AFTER a subject is selected
    // its taking place in a separate component called <TopicOptionData />


    React.useEffect(() => {
        mounted.current = true;
        if (mounted.current) {
            let updatedData = data.map((item, indx) => {
                return ({ ...item, 
                    subject: item.subject || "", 
                    category: item.category || "", 
                    type: item.type,
                    expand: false,
                    validated: "processing",
                    key: indx });
            });
            setTableData([...updatedData]);
        }
        return () => mounted.current = false;
    }, [data, page]);

    // React.useEffect(() => {
    //     if(mounted.current && tableData) {
    //         setData([...tableData]);
    //     }
    // }, [])

    const columns = React.useMemo(() => ([
        Table.EXPAND_COLUMN,
        {
            title: "",
            className: "typecheck-validate",
            dataIndex: "validated",
            key: "type-validate",
            fixed: "left",
            width: "5%",
            align: "center",
            render: (text, record, index) => {
                return <UseValidation record={record} index={index} tableData={tableData} setTableData={setTableData} />
                // return <SomeFunctionWhichValidates tableData={tableData} />
            }
        },
        {
            title: "Question",
            className: "question-cell",
            key: "question",
            dataIndex: "question",
            fixed: 'left',
            ellipsis: true
        },
        // { title: "Option no 1", key: "option1", dataIndex: "option },
        // { title: "Option no 2", key: "option2", dataIndex: "option2 },
        // { title: "Option no 3", key: "option3", dataIndex: "option3 },
        // { title: "Option no. 4", key: "option4", dataIndex: "option4 },
        {
            title: "Subject",
            key: "subject",
            align: "center",
            dataIndex: "subject",
            render: (_, __, index) => {
                return <Select
                    style={tableData[10*page.current + index]?.subject? {maxWidth: 180, minWidth: 100}: {maxWidth: 180, minWidth: 100, ...errorStyle}}
                    placeholder="Assign a subject"
                    bordered={false}
                    value={ tableData[10*page.current + index].subject || undefined }
                    onChange={(change) => {
                        if (mounted.current) {
                            tableData[10*page.current + index].subject = change;
                            tableData[10*page.current + index].category = "";
                            setData([...tableData]);
                        }
                    }}
                    options={parsedSubjects}
                />
            }
        },
        {
            title: "Topic",
            key: "topic",
            align: "center",
            dataIndex: "topic",
            render: (_, { subject }, index) => {
                return <TopicOptionData tableData={tableData} 
                    setData={setData}
                    subjectList={parsedSubjects}
                    subjectId={subject} 
                    index={10*page.current + index} 
                />
            }
        },
        {
            className: "question-type-column",
            title: "Question Type",
            key: "type",
            dataIndex: "type",
            align: "center",
            render: (_, __, index) => {
                return <Select
                    style={tableData[10*page.current + index]?.type? null: errorStyle}
                    placeholder="Assign a question type"
                    bordered={false}
                    value={ tableData[10*page.current + index].type || undefined }
                    dropdownStyle={{
                        textAlign: 'center'
                    }}
                    dropdownMatchSelectWidth={170}
                    onChange={(change) => {
                        if (mounted.current) {
                            tableData[10*page.current + index].type = change;
                            const newData = formNewOptionProperty(tableData[10*page.current + index], "typeChange");
                            // console.log(newData);
                            setData([...tableData]);
                            expandableRowSwitcher(10*page.current + index, "typeChange");
                        }
                    }}
                    options={parsedQueTypes}
                />
            }
        },
        {
            className: "complexity-column",
            title: "Complexity",
            key: "complexity",
            dataIndex: "complexity",
            align: "center",
            render: (_, __, index) => {
                const complex = tableData[10*page.current + index]?.complexity;
                return <Select
                    style={complex === "1" || complex === "2" || complex === "3"? null : errorStyle}
                    placeholder="Assign the complexity"
                    bordered={false}
                    value={tableData[10*page.current + index]?.complexity || undefined}
                    onChange={(change) => {
                        if (mounted.current) {
                            tableData[10*page.current + index].complexity = change;
                            setData([...tableData]);
                        }
                    }}
                    options={[
                        { label: <ComplexityAvatar name="easy" />, value: "1", key: 1 },
                        { label: <ComplexityAvatar name="med" />, value: "2", key: 2 },
                        { label: <ComplexityAvatar name="diff" />, value: "3", key: 3 }
                    ]}
                />
            }
        },
        {
            title: "Action",
            key: "action",
            align: "center",
            width: "8%",
            fixed: "right",
            render: (_, __, index) => {
                return <Space>
                    <span className='center-flex' onClick={() => deleteIndexEntry(index)}>
                        <DeleteIcon />
                    </span>
                </Space>
            }
        }
    ]));

    function deleteIndexEntry(index) {
        if(page.current > 0 && (tableData.length - 1) <= 10*page.current) { setPage(prev => ({current: prev.current - 1})); }
        const ar = tableData.filter((__, i) => i !== (10*page.current + index));
        setTableData(() => [...ar]);
        setData([...ar]);
    }

    function expandableRowSwitcher(index, calledFrom = "") {
        let mutableArray;
        let duplicate = expandedRows;
        const indexFound = duplicate.findIndex((item) => item === index);
        if(calledFrom) {
            setTimeout(() => {
                const tableRow = document.querySelector(`.bulk-upload-module .expanded-row-${index}`);
                tableRow.scrollIntoView({behavior: "smooth", block: "start"});
            }, 0);
            if(indexFound >= 0) {
                return;
            }
            if(indexFound < 0) {
                mutableArray = expandedRows;
                mutableArray.push(index);
            }
        }
        if(!calledFrom) {
            if(indexFound >= 0) mutableArray = duplicate.filter((_, indx) => indx !== indexFound);
            if(indexFound < 0) {
                mutableArray = expandedRows;
                mutableArray.push(index);
            }
        }
        setExpandedRows(() => [...mutableArray]);
    }

    // row selection feature reserved for future
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys) => {
            console.log('selectedRowKeys changed: ', newSelectedRowKeys);
            setSelectedRowKeys(newSelectedRowKeys);
        }
    };

    if(data.length > 0 && tableData.length === 0) {
        return <div className='loading-message center-flex m-1-0'>
            Sorting through the questions..
        </div>
    }

    return (
        <div>
            <Table
                columns={columns}
                // title={() => <>{selectedRowKeys.length} selected</>} // this maybe used in future for more editing option
                title={() => <>{sessionStorage.getItem("currentClassName")
                    ? <Alert message={sessionStorage.getItem("currentClassName") + " class active"} showIcon />
                    : <Alert message="Please select a class before continuing" type='warning' showIcon/>}</>}
                loading={tableDataLoading}
                // rowSelection={rowSelection} // this maybe used in future for more feature in order to edit
                pagination={{
                    current: page.current + 1,
                    size: 'small',
                    onChange: (current, pageSize) => {
                        setPage(prev => ({current: current-1}));
                    },
                    defaultPageSize: 10,
                    hideOnSinglePage: true,
                    showSizeChanger: false
                }}
                expandable={{
                    expandedRowRender: (record, index) => (
                        <EditUploadedQuestion record={record} index={page.current*10 + index} setData={setData} expandedRows={expandedRows} />
                    ),
                    fixed: "left",
                    expandedRowKeys: expandedRows,
                    onExpand: (expanded, record) => {
                        expanded? tableData[record.key].expand = true: tableData[record.key].expand = false;
                    },
                    expandedRowClassName: (record, _, __) => { return `expanded-row-${record.key}` },
                    expandIcon: ({ expanded, onExpand, record }) =>
                        {
                            return expanded ? (
                                <EyeFilled onClick={e => {
                                    // onExpand(record, e);
                                    expandableRowSwitcher(record.key);
                                }} />
                            ) : (
                                <EyeOutlined onClick={e => {
                                    // onExpand(record, e);
                                    expandableRowSwitcher(record.key);
                                }} />
                            )
                        },
                    rowExpandable: (record) => record.name !== 'Not Expandable',
                }}
                dataSource={tableData}
                scroll={{
                    x: 1200,
                    y: 290,
                }}
            />
        </div>
    );
}

export default QuestionListTable;
