import { useState, useEffect } from 'react';

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

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

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

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

import './menu-dashboard-card.scss';

/** Title */
const { Title } = Typography;

/**
 * Dashboard Card
 *
 * @param {*} param0
 * @returns {string}
 */
export default function MenuDashboardCard({ record, selectedCardId, callback, onSelect , style }) {
  const isSelected = selectedCardId === record.id;

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

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

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

  /**
   * useEffect Hook
   *
   * Executes the `executeQuery` function when the component mounts.
   */

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

  /**
   * Executes the dashboard query and sets the result state with the fetched data.
   * Handles both success and error responses.
   *
   * @param {string|number} id - The ID used to execute the query and fetch dashboard data.
   * @returns {void} This function does not return anything.
   */
  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' });
      });
  }

  /**
   * Parses `other_details` from the record and applies styles.
   * If `other_details` exists, it is parsed as JSON; otherwise, an empty object is used.
   *
   * @type {Object}
   */
  let styles = {};

  if (record.other_details) {
    styles = JSON.parse(record.other_details);
  }

  /**
   * Opens a pop-up modal and passes the record to the callback function.
   *
   * @param {Object} record - The record data to be passed.
   * @returns {void} This function does not return anything.
   */
  function viewPopQueryModal(record) {
    callback(record);
    // setSelectedCardId(isSelected ? null : record.id); // toggle selection
    onSelect ()
  }

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

  var props = {};
  /**
   * Stores component properties, including the loading state.
   *
   * @type {Object}
   */

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

  /**
   * Renders different dashboard tiles based on the `tiletypeptr` of the record.
   *
   * @param {Object} record - The record containing the tile information and tile type.
   * @returns {JSX.Element | string} The rendered dashboard tile component or an empty string.
   */
  function displayDashboardTile(record) {
    // console.log(result);
    switch (record.tiletypeptr) {
      case 'BASIC':
        // return <StatisticCard result={result[0]} {...props} />;
        return (
          <div
            //  className="statistic-card-container"
            className={`statistic-card-container ${'selected'}`}
          >
            <StatisticCard result={result[0]} {...props} />
          </div>
        );

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

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

      default:
        return '';
    }
  }

  function onCancel() {
    setVisible(false);
  }

  return (
    <>
      {loading ? (
        <Skeleton />
      ) : (
        <div
          // className="menu-dashboard-card card"
          className={`menu-dashboard-card card ${isSelected ? 'selected' : ''}`}
          onClick={() => viewPopQueryModal(record)}
        >
          <Title style={{ fontSize: '10px' }} level={5}>
            {record.text}
          </Title>

          {result.error ? (
            <>
              <Alert message="Error loading values" type="error" showIcon />
            </>
          ) : (
            <>{loading ? <Skeleton /> : displayDashboardTile(record)}</>
          )}
          <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>
        </div>
      )}
    </>
  );
}
