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

import {animationControls, motion, useAnimation} from "framer-motion";

import {
  boxVariants,
  barsVariant,
  barVariant,
  buttonsVariant,
  buttonVariant
} from "./animations"

import { Modal, Col, Skeleton, Alert, Typography } from 'antd';

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

import { PopQueryDashboard } from './../../../'

import { StatisticCard, BasicTable, ErrorBoundary } from './../../../../lib';


const { Title } = Typography;

/**
 * Dashboard Card
 *
 * @param {*} param0
 */
export default function DashboardCard({ record }) {

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

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

    const [result, setResult] = useState({});

    useEffect(() => {
        executeQuery(record.id);
    }, []);

    function executeQuery(id) {
        setLoading(true);

        // Execute dashboard
        Dashboard.execDashboard(id)
            .then((response) => {
                var data = {};

                let reportData = {};

                // @todo 
                // We are in the transition of incorporating the api bootstrap core for nura and 
                // other projects , so we are handling both here . 
                // When the reporting module is build , we have to consider its changes . 

                if (response.result) {

                    reportData = response.result[0];

                } else {

                    if (response[0]) {

                        reportData = response[0];
                    }
                }

                setResult(reportData);

                setLoading(false);
            })
            .catch(() => {
                setResult({ error: 'Error' });
            });
    }

    let styles = {};

    if (record.other_details) {

        styles = JSON.parse(record.other_details)

    }

    /**
     *
    */
    function viewPopQueryModal(id) {
        setVisible(true);
    }

    /**
     *
     */
    function executePopQuery() { }

    var props = {};

    if (loading) {
        props.loading = true;
    }

    /**
     * Display Each card according to graph type
     */
    function displayDashboardTile(record) {
        // console.log(result);

        switch (record.tiletypeptr) {
            case 'BASIC':
                return <StatisticCard result={result[0]} {...props} />;

            case 'TABLE':
                return <BasicTable styles={styles} result={result} {...props} />;

            case 'LINEGPH':
                return null;
            // return <BarGraph data={result} {...props} />;

            default:
                return '';
        }
    }

    let span = 6;

    switch (record.tiletypeptr) {
        case 'BASIC':
            break;

        case 'TABLE':
            span = 24;
            break;

        case 'LINEGPH':
            span = 24;
            break;

        default:
        // return '';
    }

    function onCancel() {
        setVisible(false);
    }

    //Animations//
    const MotionLink = motion(Col);
    const boxControls = useAnimation();

    async function animate(){
        await boxControls.start("entered");

        //await boxControls.start("show");
    } 

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

    return (

        <MotionLink 
        variants={boxVariants}
        initial={{y: 50, opacity: 0}}
        animate={{y: 0, opacity: 1}}
        transition={{delay: 0.5, duration: 0.4, ease: [.62,.28,.23,.99]}}
        className="dashboard-card card card-shadow" span={span} lg={{ span: span }} xs={{ span: 24 }} key={record.id}>
            <Title level={5}>{record.text}</Title>

            {result.error ? (
                <>
                    <Alert message="Error loading values" type="error" showIcon />
                </>
            ) : (
                <>{loading ? <Skeleton /> : displayDashboardTile(record)}</>
            )}

            <span className="link" onClick={viewPopQueryModal}>View</span>

            <Modal
                width="80%"
                destroyOnClose={true}
                visible={visible}
                title={record.text}
                footer={null}
                okText="Create"
                cancelText="Cancel"
                onCancel={onCancel}
                onOk={() => { }}
            >
                <PopQueryDashboard record={record} id={record.id} />
            </Modal>
        </MotionLink>

    );
}
