/**
 * ExtraInfo component executes the script data
 * 
 * @description 
 * @author Sneha T
 */

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

import { Table, Skeleton } from 'antd';

import { Dashboard } from '../../models';

// import './extra-info.scss'


export default function ExtraInfo({ item, record }) {

    let displayColumns = item.display_columns;

    // To store selected values
    const [loading, setLoading] = useState(true);

    // To store columns of tables
    const [columns, setColumns] = useState([]);

    // To store api result
    const [result, setResult] = useState([]);
    /**
    * 
    * 
    * Manage initial render
    */
    useEffect(() => {
        getSelectedItem(item)

        if (item.display_columns) {

            displayColumns = JSON.parse(displayColumns);

            setColumns(displayColumns)

        }

    }, [item])

    /**
    * Columns for table
    */
    const cols = [
        ...[
            {
                title: '#',
                dataIndex: 'index',
                render: (value, item, index) => index + 1,
                key: 'ColumnIndex'
            },
        ],

        //Mappping through columns
        ...columns.map((entry) => {

            return {
                render: (record) => {

                    if (entry.render) {

                        return entry.render(record);

                    } else {

                        return record[entry.field]
                    }
                },
                field: entry.field,
                title: entry.title,
                key: entry.field,
            };

        }),
    ]
    /**
     * Function to get selected Item
     */
    async function getSelectedItem(item) {

        setLoading(true);

        let formBody;

        formBody = {
            ...record,
            submode: item.submode
        };


        return await Dashboard.getSelectedExtraInfo(formBody).then((result) => {

            setResult(result)


            setLoading(false)

        })


    }

    return (
        <>

            {loading ? (
                <>
                    <Skeleton active />
                </>
            ) : (

                <Table
                    scroll={{ x: true }}
                    // rowKey={record => record.da_id}
                    dataSource={result}
                    columns={cols}
                    pagination={
                        false
                    }

                />

            )}
        </>
    );
};
