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

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

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

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

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

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

const { Title } = Typography;

const { Search } = Input;

const PageList = ({ history, model, match, columns, relativeAdd = false, additional_queries = [], disableAddModal = model.disableAddModal, disableEditModal = model.disableEditModal }) => {

    const actions = [];

    match = useParams();

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

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

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

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

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

    const [config, setConfig] = useState({});

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

    useEffect(() => {

        getRecords();

    }, []);

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

        setLoading(true);

        // Get the records
        return model.get({})

            .then((res) => {

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

                if (Array.isArray(result)) {

                    setRecords(result);

                }

                setLoading(false);

            })
            .catch((error) => {

                setLoading(false);

                console.log(error);
            });
    };


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

    function closeModal() {
        setVisible(false);
    }

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

    /**
     * Edit the record
     * 
     * @param record 
     */
    function edit(record) {

        setSingle({ ...record });

        setVisible(true);
    }


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

        }
    });

    const cols = model.getColumnConfig({ options, model, actions: [], callback: getRecords, edit })

    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 />}
                                />

                                {!model.ModalAddComponent ? null : (
                                    <Button type="dashed" onClick={() => {

                                        // setSingle(record);

                                        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={records} />
                        )}
                    </>
                </>
            )}

            {/* Add Modal */}
            <Modal width="80%" destroyOnClose confirmLoading={loading} visible={visible} onCancel={closeModal} footer={null}>
                <model.ModalAddComponent
                    config={config}
                    match={match}
                    model={model}
                    additional_queries={additional_queries}
                    formContent={single}
                    callback={() => {
                        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 PageList;

