/**
 * Generic List accepts an array of fields to update any resource
 */

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

import { Link, useParams, useLocation } from 'react-router-dom';

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

import { Table, Button } from './../../../../lib';

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

const UserList = ({ model, match, relativeAdd = false, additional_queries = [], disableAddModal = model.disableAddModal ,...props}) => {

    const actions = [];

    match = useParams();

    // Block to get the url params #Note Location search is not working
    let location = useLocation();

    const query = new URLSearchParams(location.search);

    console.log(query.get('step'));

    let step = parseInt(query.get('step')) || 1;
    // 

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

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

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

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

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

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

    const { Search } = Input;

    useEffect(() => {

        getRecords();

    }, []);

    /**
     *
     */
    const getRecords = () => {

        let firstStepQueries = [{
            field: 'step',
            value: step
        }]

        let config = {
            queries: [
                ...additional_queries,
                //  ...firstStepQueries
            ],
        }

        if (!additional_queries.length) {

            //  config.queries.push({
            //      field: 'header_id',
            //      value: null
            //  })
        }

        setLoading(true);

        // Get the records
        return model.get(config)

            .then((response) => {

                // setRecords(res.result);
                var result = response.result;

                // if (id) {

                //     var filtered = res.result.filter((record) => record.header_id = id)

                // }


                setRecords(result);

                setLoading(false);

            })
            .catch((error) => {

                setLoading(false);

                console.log(error);
            });

    };


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

    /**
     * Function hides the modal
     * 
     * @param reload 
     */
    function closeModal() {

        setVisible(false);

        // if (reload) {
        //     getRecords();
        // }
    }

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

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

            getRecords();

        }).catch((error) => {

            setLoading(false);

            console.log(error);

        })
    }

    const cols = [
        ...[
            {
                title: '#',
                dataIndex: 'index',
                render: (value, item, index) => 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);
                        }
                        // 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">

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

                                    setSingle({ ...record });

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

                            {/* Copy */}
                            {!model.ModalAddComponent ? null : (
                                <Button size={'small'} onClick={() => {

                                    setSingle({
                                        ...record,
                                        id: null,
                                        copy: true
                                    });

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

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


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

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

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

    /**
     * Function to store search value
     */
    function onSearch(event) {
        setQueryValue(event.target.value);
    }

    /**
    * Search in candidate visit List
    */
    let filtered = records.filter(record => {

        let searchText = queryValue.toUpperCase();

        if (queryValue) {

            if (record.name !== null) {

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

                    return true;
                }
            }
        } else {

            return true;

        }
    });

    return (

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

                    <Search
                        placeholder="Enter Search Value"
                        allowClear
                        // value={query}
                        style={{ width: 300, marginTop: '10px', marginBottom: '20px' }}
                        onChange={onSearch}
                    />
                    {/* <Title level={4}>{model.name}</Title> */}

                    {/* <p>{loading ? 'Loading records' : `${record.length} records`}</p> */}
                </div>

                <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} size={'small'}>
                                    <ReloadOutlined />
                                </Button>

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

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

                                        setSingle({});

                                        setVisible(true);
                                    }}>
                                        Add
                                    </Button>
                                )}
                            </Space>
                        </div>
                    </div>
                </div>
            </div>

            {/* Table Header Ends */}

            {loading ? (
                <Skeleton />
            ) : (
                <>
                    <>
                        {!view ? (
                            <div className='card card-shadow'>
                                <Table
                                    // rowKey={obj => obj.id}
                                    // ref={(ref) => { tableRef = ref }}
                                    loading={loading}
                                    data={filtered ? filtered : records}
                                    columns={cols}
                                ></Table>
                            </div>
                        ) : (
                            <CardList model={model} data={filtered ? filtered : records} />
                        )}
                    </>
                </>
            )}

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

                        getRecords();
                    }}
                />
                {/* <FormCreator formContent={{ [model]: {} }} modelIndex="requestId" model={model} onSubmit={createRecord} config={step} /> */}
            </Modal>


        </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 UserList;

