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

import { Card, Button, Typography, Table, Skeleton, Input } from 'antd';

import { Location, Apiutils, FormCreator, GlobalContext, ExportReactCSV, getExportData } from 'soxo-firebase-core';

import { CoreScripts } from './../../../../models/'

import moment from 'moment-timezone';

import './reporting-dashboard.scss';

import { ReloadOutlined } from '@ant-design/icons';

const { Search } = Input;

const { Title, Text } = Typography;

export default function ReportingDashboard({ match }) {

    // console.log(props);

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

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

    const { pageno, id } = match.params; //Get pagination number

    const { CustomModels = {} } = useContext(GlobalContext);


    // let loadedModel = require('./../../../models/');

    // let details = [
    //     { "field": "start", "caption": "Date", "type": "date" },
    //     { "field": "end", "caption": "Date", "type": "date" },
    //     { "options": [0, 1, 2], "caption": "Quantity", "type": "select" },
    //     { "caption": "Time", "type": "datetime" },
    //     { "caption": "Appointments", field: 'appointment_name', "type": "reference-select", modelName: 'Appointments', label: 'da_fname' }
    // ]


    const [details, setDetails] = useState([]);

    const [columns, setColumns] = useState([]);

    const [summaryColumns, setSummaryColumns] = useState([]);

    const [patients, setPatients] = useState([]); //Patients list array

    //PatiantData fetching function
    async function getPatientDetails() {

        setPatients([])

        setLoading(true);

        CoreScripts.getRecord({ id }).then(({result}) => {

            prepareInputParameters(result.input_parameters);

            setColumns(JSON.parse(result.display_columns));

            if (result.summary_columns) {

                setSummaryColumns(JSON.parse(result.summary_columns))

            }

            setConfig(result);

            setLoading(false);

        });
    }

    /**
     * Some parameters would need binding with the model
     * 
     * @param {*} input_parameters 
     */
    function prepareInputParameters(input_parameters) {

        let parameters = JSON.parse(input_parameters);

        parameters = parameters.map((record) => {

            if (['reference-select', 'reference-search'].indexOf(record.type) !== -1) {

                // let model = "";
                let model = CustomModels[record.modelName];

                return {
                    ...record,
                    model,
                    required: true
                }
            } else {
                return {
                    ...record,
                    required: true
                }
            }

        })

        setDetails([...parameters]);

    }

    useEffect(() => {

        getPatientDetails();

    }, []);

    useEffect(() => {

        getPatientDetails();

    }, [match.params]);


    function refresh() {
        getPatientDetails();
    }

    const onFinish = (values) => {

        if (values.date) {
            values.date = moment(values.date).format('YYYY-MM-DD')
        }
        let formBody = {
            "body": values
        }
        return CoreScripts.getReportingLisitng(id, formBody).then((result) => {

            setPatients(result[0]);
            return;

        });
    };

    let model = {
        "fields": details
    }

    return (
        <section className="reporting-dashboard card">
            {/* Page Header */}
            <div className="page-header">
                <div className="left">
                    <Title style={{ marginBottom: '0px' }} level={4}>
                        {config.caption || 'Report'}
                    </Title>
                </div>

                <div className="right">
                    <div className="date-and-fltr">
                        <Button onClick={refresh} type="secondary" size={'small'}>
                            <ReloadOutlined />
                        </Button>
                    </div>
                </div>
            </div>
            {/* Page Header Ends */}

            {/* Content Below */}
            {
                loading ?
                    (
                        <>
                            <Skeleton active />
                        </>
                    )
                    :
                    (
                        <>
                            <div>

                                <Card className="form-card" style={{ padding: '10px 10px' }}>
                                    {
                                        details && details[0] ?
                                            <FormCreator
                                                fields={details}
                                                layout="inline"
                                                formContent={{ [model]: {} }}
                                                modelIndex='requestId'
                                                model={model}
                                                onSubmit={onFinish}
                                                callback={() => {

                                                    // history.goBack();

                                                }}
                                            />
                                            :
                                            null
                                    }
                                </Card>
                            </div>
                            <GuestList patients={patients} columns={columns} summaryColumns={summaryColumns} />
                        </>
                    )
            }
        </section>
    );
}

function GuestList({ patients, columns, summaryColumns }) {

    var [query, setQuery] = useState('');

    const [data, setData] = useState([]);

    const { user = {}, isMobile, dispatch } = useContext(GlobalContext);

    const [view, setView] = useState(isMobile ? true : false); //Need to check this condition

    const cols = [
        ...[
            {
                title: '#',
                dataIndex: 'index',
                render: (value, item, index) => index + 1,
            },
        ],
        ...columns.map((entry) => {
            // if (entry.sort) {
            //     return {
            //         render: (record) => {
            //             if (entry.render) {
            //                 return entry.render(record);
            //             } else {
            //                 return record[entry.dataIndex]
            //             }
            //         },
            //         title: entry.title,
            //         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);
                    } else {
                        // return entry.field.split('.').reduce((acc, part) => acc && acc[part], record);
                        return record[entry.field]
                    }
                },
                field: entry.field,
                title: entry.title,
                key: entry.field,
            };
            // }
        }),
        // ...[
        //     {
        //         title: '',
        //         key: 'action',
        //         render: (text, record) => {
        //             let detail = model.slice(0, model.length - 1);

        //             return (
        //                 <Space size="middle">
        //                     {!schema.hideView && !actions.length ? <Link to={`/${city}/${model}/${text.id}`}>View</Link> : null}

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

    // Get the export data 
    let exportData = getExportData(patients, columns);

    console.log(exportData);

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


    function onSearch(event) {

        setQuery(event.target.value);
    }


    useEffect(() => {
        let data = patients.map((entry) => {
            entry.rowIndex = entry.opb_id;

            entry.dispatch = dispatch;

            return entry;
        });

        setData(data);
    }, [patients]);


    let filtered = data.filter((record) => {

        if (query) {

            // Keys
            let keys = Object.keys(record);

            let flag = false;

            keys.forEach((key) => {

                let ele = record[key]

                if (ele && typeof ele === 'string' && ele.toLowerCase().indexOf(query.toLowerCase()) !== -1) {

                    flag = true;
                }
            })

            return flag;

        } else {
            return true;
        }
    })

    return (
        <>
            <div className="table-header">

                <div>

                    <Search placeholder="Enter Search Value" allowClear onChange={onSearch} />

                    <p className="size-hint">{patients.length} records.</p>

                </div>

                <div>

                    {/*table data export to csc component*/}
                    {patients && <ExportReactCSV csvData={exportData} />}

                </div>

            </div>

            <div>
                {/* {view ? (
                    <>
                        <CardList dataSource={data} columns={columns} />
                    </>
                ) : (
                    <> */}
                <Card>
                    <Table
                        size="small"
                        scroll={{ x: true }}
                        rowKey={(record) => record.OpNo}
                        dataSource={filtered}
                        columns={cols}
                        pagination={false}
                        summary={(pageData) => {

                            // Variable to save the summary data
                            let summary = {};

                            let summaryColumns = [{ "field": "opb_amt", "title": 'Amount' }, { "field": "opb_netamt", "title": 'Net Amount' }];

                            let tableColumns = cols;

                            // Creating a copy of columns to append the summary configuration that is needed to set
                            tableColumns.forEach((record, index) => {

                                summaryColumns.forEach((inner) => {

                                    if (record.field === inner.field) {

                                        tableColumns[index].summary = inner;

                                    }
                                })
                            })

                            // Initialize
                            summaryColumns.map((item) => {
                                return summary[item.field] = 0
                            })

                            // Find the total
                            summaryColumns.map((item) => {
                                pageData.forEach((entry) => {
                                    return summary[item.field] = summary[item.field] + entry[item.field]
                                })
                            })

                            console.log(pageData, summary);

                            return (
                                <>
                                    <Table.Summary.Row>

                                        {
                                            tableColumns.map((column, key) => {

                                                return (<Table.Summary.Cell key={key}>

                                                    {
                                                        column.summary
                                                            ?
                                                            <>

                                                                {summary[column.summary.field]}

                                                            </>
                                                            :
                                                            null
                                                    }
                                                </Table.Summary.Cell>)

                                            })
                                        }

                                    </Table.Summary.Row>
                                </>
                            );
                        }}
                    />
                </Card>
                {/* </> */}
                {/* )} */}
            </div>
        </>
    );
}

//Mobile view card Section
function CardList({ dataSource, columns, url }) {
    const { user = {}, isMobile, dispatch } = useContext(GlobalContext);

    function onClick(item) {
        Location.navigate({
            url: `/lab-detail/${item.BillID}`,
        });

        dispatch({ type: 'index', payload: item.rowIndex });
    }

    return dataSource.map((item, index) => {
        // to={`/lab-detail/${item.BillID}`}
        return (
            <div
                key={index}
                className="report-item"
                onClick={() => {
                    onClick(item);
                }}
            >
                <GuestCard record={item} />
            </div>
        );
    });
}

function GuestCard({ record }) {
    return (
        <Card className="card vehicle-card">
            <div className="card">
                <h2 className="title">{record.PName}</h2>

                <h4 className="values">{record.OpNo}</h4>

                <h3 className="values">{record.Test}</h3>

                <h3 className="values">Primary Result : {record.PrimaryResult || 'Pending'}</h3>

                <Text type="secondary">{record.Mobile}</Text>

                <h4 className="values">{record.Date}</h4>
            </div>
        </Card>
    );
}

