import React, { useState, useEffect } from 'react';

import { Link } from 'react-router-dom';

import { Skeleton, Typography, Space,Input, Switch, Modal, Popconfirm } from 'antd';

import { Card, Button, TableComponent } from './../../../../lib/';

import './generic-list.scss';

import { ReloadOutlined, OrderedListOutlined, PicCenterOutlined, DeleteOutlined } from '@ant-design/icons';

const { Title } = Typography;

const { Search } = Input;


const GenericListAPI = ({ model, config = {}, relativeAdd = false, additional_queries = [] }) => {

    const actions = [];

    // Options for the list
    const [options, setOptions] = useState({
        page: 1,
        size: 20,
    });

    const [view, setView] = useState(false);

    const [loading, setLoading] = useState(false);

    const [records, setRecords] = useState([]);

    const [visible, setVisible] = useState(false);

     var [queryValue, setQueryValue] = useState('');

    const [single, setSingle] = useState({});

    const cols = [
        ...[
            {
                title: '#',
                dataIndex: 'index',
                render: (value, item, index) => (options.page - 1) * options.size + index + 1,
            },
        ],
        ...model.columns.map((entry) => {
            if (entry.sort) {
                return {
                    render: (record) => {
                        if (entry.render) {
                            return entry.render(record);
                        } else {
                            return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                        }
                    },
                    title: entry.caption,
                    key: entry.field,
                    // sorter: (a, b) => entry.sort(a, b),
                    sortDirections: ['ascend', 'descend', 'ascend'],
                };
            } else {
                return {
                    render: (record) => {
                        if (entry.render) {
                            return entry.render(record);
                            // return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                        } else {
                            return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                        }
                        // return record[entry.field]
                    },
                    title: entry.caption,
                    key: entry.field,
                    // dataIndex: entry.field,
                };
            }
        }),
        ...[
            {
                title: '',
                key: 'action',
                render: (text, record) => {
                    return (
                        <Space size="middle">


                            {/* Delete Icon */}
                            <Popconfirm title="Are you sure" onConfirm={() => {
                                onDelete(record);
                            }}>
                                <Button size="small" type="dashed">
                                    <DeleteOutlined />
                                </Button>
                            </Popconfirm>
                            {/* Delete Icon */}


                            {/* Edit */}
                            {!model.ModalAddComponent ? null : (
                                <Button size="small" type="dashed" onClick={() => {

                                    setSingle({ ...record });

                                    setVisible(true);
                                }}>
                                    Edit
                                </Button>
                            )}
                            {/* Edit Ends */}

                            {/* {!model.hideView && !actions.length ? <Link to={`/${model.name}/${text.id}`}>View</Link> : null} */}

                            {!model.hideView && !actions.length ? <Link to={`/${model.link}/${record.id}`}>View</Link> : null}

                            {/* {actions.map((action) => (
                                <Link to={action.url(record)}>{action.caption}</Link>
                            ))} */}
                        </Space>
                    );
                },
            },
        ],
    ];

    useEffect(() => {
        getRecords();
    }, []);

        /**
    * Function to store search value
    */
        function onSearch(event) {
            setQueryValue(event.target.value);
        }
    
       
     /**
    * Search in menu 
    */
     let filtered = records.filter(record => {
    

        let searchText = queryValue.toUpperCase();

        if (queryValue) {

            if (record.role.name !== null) {

                if (record.role.name?.toUpperCase().indexOf(searchText) != -1) {

                    return true;
                }
            }
        } else {

            return true;

        }
    });

  
    /**
     * 
     */
    function getRecords() {
        setLoading(true);

        config = {
            ...config,
            queries: [
                ...additional_queries
            ]
        }

        // Get the records
        model
            .get(config)
            .then((result) => {
                if (result) {

                    if (Array.isArray(result.result)) {

                        setRecords(result.result);

                    }

                    console.log(model);

                    setLoading(false);
                }
            })
            .catch((error) => {
                setLoading(false);

                console.log(error);
            });
    }

    /**
     * On delete of each record 
     */
    function onDelete(record) {

        model.delete(record).then(() => {
            getRecords()

        }).catch((error) => {

            setLoading(false);

            console.log(error);

        })
    }

    function changeView(result) {
        setView(result);
    }

    function closeModal() {
        setVisible(false);
    }

    return (
        <div className="generic-list">
            {/* Table Header */}
            <div className="table-header">


                <div className="table-bar">
                    {/* Table Filters */}
                    <div className="table-filters">
                        <Space direction="vertical" size={12}></Space>
                    </div>
                    {/* Table Filters Ends */}

                    <div className="table-actions">
                        <div className="button-container">
                            <Space size="small">
                                <Button onClick={getRecords} type="secondary" size={'small'}>
                                    <ReloadOutlined />
                                </Button>
                                
                                <Search
                                placeholder="Enter Search Value"
                                allowClear
                                style={{ width: 300, marginBottom: '0px' }}
                                onChange={onSearch}
                            />

                                <Switch
                                    defaultChecked
                                    onChange={changeView}
                                    checked={view}
                                    checkedChildren={<OrderedListOutlined />}
                                    unCheckedChildren={<PicCenterOutlined />}
                                />

                                {
                                    !relativeAdd
                                        ?
                                        <Link to={`/${model.link}`}>
                                            <Button size="small">
                                                Add
                                            </Button>
                                        </Link>
                                        :
                                        <Button size="small" type="dashed" onClick={() => setVisible(true)}>
                                            Add
                                        </Button>
                                }

                            </Space>
                        </div>
                    </div>
                </div>
            </div>

            {/* Table Header Ends */}

            {loading ? (
                <Skeleton />
            ) : (
                <>
                    <>
                        {!view ? (
                            <Card>
                                <TableComponent
                                    // rowKey={obj => obj.id}
                                    // ref={(ref) => { tableRef = ref }}
                                    loading={loading}
                                    dataSource={filtered? filtered : records}
                                    scroll={{ x: true }}
                                    columns={cols}
                                ></TableComponent>
                            </Card>
                        ) : (
                            <CardList model={model} data={filtered ? filtered:records} />
                        )}
                    </>
                    <p>{loading ? 'Loading records' : `${records && records.length ? records.length : '0'} records`}</p>

                </>

            )}

            {/* Add Modal */}
            <Modal destroyOnClose={true} confirmLoading={loading} visible={visible} onCancel={closeModal} footer={null}>
                <model.ModalAddComponent
                    model={model}
                    additional_queries={additional_queries}
                    formContent={single}
                    callback={() => {

                        closeModal();

                        getRecords();
                    }}
                />
            </Modal>

            {/* Add Modal Ends */}
        </div>
    );
};

function CardList({ model, data, url, ...props }) {
    return data.map((record, index) => {
        return <model.Card record={record} model={model} index={index} key={index} {...record} {...props} />;
    });
}

export default GenericListAPI;
