/**
 * MenuDashBoard Component
 *
 * This component is responsible for rendering the menu dashboard.
 * It fetches dashboard data based on user roles and displays them using `MenuDashboardCard` components.
 */

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

import { Skeleton, Row } from 'antd';

import { GlobalContext, Card } from './../../lib/';

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

import MenuDashboardCard from '../../modules/dashboard/components/dashboard-card/menu-dashboard-card';

import './menu-dashboard.scss';

/**
 * MenuDashBoard Component
 *
 * Renders the dashboard menu based on the provided `dashBoardIds`.
 * Fetches dashboard data and updates the UI accordingly.
 *
 * @param {Object} props - The component props
 * @param {Array} props.dashBoardIds - List of dashboard IDs to fetch data for
 * @param {Function} props.callback - Callback function for handling dashboard interactions
 * @returns {JSX.Element} The rendered MenuDashBoard component
 */
export default function MenuDashBoard({ dashBoardIds, callback }) {
  const { user = {} } = useContext(GlobalContext);

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

  const [list, setList] = useState([]);

  const [selectedCardId, setSelectedCardId] = useState(false);

  /**
   * useEffect Hook
   *
   * Triggers the `getDashboard` function whenever the `user` object changes.
   * Ensures dashboard data is fetched whenever a user logs in or changes.
   */
  useEffect(() => {
    if (dashBoardIds) {
      getDashboard(); //Patiant list get function
    }
  }, [user]);

  /**
   * getDashboard Function
   *
   * Fetches the dashboard menu items based on `dashBoardIds`.
   * Updates the `list` state with the fetched data.
   */
  async function getDashboard() {
    setLoading(true);

    // Check if there are dashboard IDs to fetch data for
    if (dashBoardIds.length > 0) {
      await Dashboard.loadMenuDashboards(dashBoardIds).then((response) => {
        let apiResponse = {};

        // @todo When the reporting tool is build , we have to consider all of these
        if (response.result && response.result.length) {
          apiResponse = response.result;
        } else if (response && response.length) {
          apiResponse = response;
        }
        // Group by groupPtr inside other_details
        const groupedData = {};

        apiResponse.forEach((item) => {
          try {
            const otherDetails = item.other_details ? JSON.parse(item.other_details) : {};

            const groupPtr = otherDetails.groupPtr;

            const groupCaption = otherDetails.groupcaption || ''; // default empty string if not available

            if (groupPtr) {
              if (!groupedData[groupPtr]) {
                groupedData[groupPtr] = {
                  groupPtr,
                  groupCaption,
                  // colorCode,
                  dashboards: [],
                };
              }

              // Optional: update groupCaption if it exists newly (in case not present earlier)
              if (groupCaption) {
                groupedData[groupPtr].groupCaption = groupCaption;
              }

              // Create a new dashboard item that includes style and colorCode
              const dashboardItem = {
                ...item, // Spread other properties of the item
                // style: groupStyle, // Add the group style
                // colorCode, // Add the color code
              };

              // Push the new dashboard item into the dashboards array
              groupedData[groupPtr].dashboards.push(dashboardItem);
            }
          } catch (error) {
            console.error('Error parsing other_details:', error);
          }
        });

        // Convert groupedData to array format
        const groupedArray = Object.values(groupedData);

        setList(groupedArray);

        setLoading(false);
      });
    }

    setLoading(false);
  }

  return (
    <>
      {loading ? (
        <Skeleton />
      ) : (
        <span className="menu-dashoard-section">
          <div className="menu-dashboard">
            <div className="dashboard-section" style={{ marginBottom: '10px' }}>
              {/* <Row gutter={20}>
                    {list
                      // Sort in ascending asc of id
                      .sort((a, b) => a.slno - b.slno)
                      .map((entry, key) => (
                        <MenuDashboardCard key={key} record={entry} callback={callback} />
                      ))}
                  </Row> */}
              {list.map((group) => (
                <Card key={group.groupPtr}>
                  {/* <h3>Group: {group.groupPtr}</h3> */}
                  <h3 style={{ marginBottom: '10px' }}>{group.groupCaption}</h3>

                  <Row gutter={20}>
                    {group.dashboards
                      .sort((a, b) => a.slno - b.slno)
                      .map((entry, key) => (
                        <MenuDashboardCard
                          key={key}
                          record={entry}
                          callback={callback}
                          selectedCardId={selectedCardId}
                          onSelect={() => setSelectedCardId(entry.id)}
                          // setSelectedCardId={setSelectedCardId}
                        />
                      ))}
                  </Row>
                </Card>
              ))}
              {/* </> */}
            </div>
          </div>
        </span>
      )}
    </>
  );
}
