[
    {
        "summary": "If Group is NONE AND If Hour Since Ticket Created is 0  Assign to Group Billing",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-01-23T05:22:29Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000718712,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:12:05Z",
        "name": "Copy of Copy of time trigger2",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 3,
        "conditions": "condition_set_1,all,group_id,in,,hours_since_created,is,0",
        "actions": "group_id,82000523993",
        "events": null,
        "display_id": "4ie1y-490",
        "id": 82000718712,
        "impact": 0
    },
    {
        "summary": "If Status is All closed  Set Type as Event Request",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-05-10T03:45:10Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000721051,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of r1",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 6,
        "conditions": "condition_set_1,all,status,in,8",
        "actions": "ticket_type,Event Request",
        "events": null,
        "display_id": "4ie1y-371",
        "id": 82000721051,
        "impact": 0
    },
    {
        "summary": "If Group is Test 7 Set Status as Cancel",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-05-10T06:28:46Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000721095,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of Copy of Copy of Copy of Copy of state",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 7,
        "conditions": "condition_set_1,all,group_id,in,82000660028",
        "actions": "cf_status397966,Cancel",
        "events": null,
        "display_id": "4ie1y-372",
        "id": 82000721095,
        "impact": 0
    },
    {
        "summary": "If Product is New Knowledge Base Article UI Test  Set Status as Open",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-05-10T06:33:42Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000721105,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of b1",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 8,
        "conditions": "condition_set_1,all,product_id,in,82000011880",
        "actions": "status,2",
        "events": null,
        "display_id": "4ie1y-373",
        "id": 82000721105,
        "impact": 0
    },
    {
        "summary": "If Status is Spares Required AND If Ticket Type  is Service Request AND If Product is Freshdesk AND If Order Id is 34563215 Set Group ID as 4500098",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-05-15T08:00:52Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000721487,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "bg1",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 9,
        "conditions": "condition_set_1,all,cf_status,in,Spares Required,cf_ticket_type,in,Service Request,product_id,in,82000011730,cf_order_id,is,34563215",
        "actions": "cf_group_id,4500098",
        "events": null,
        "display_id": "4ie1y-375",
        "id": 82000721487,
        "impact": 0
    },
    {
        "summary": "If Customer Response is Yes Set Brand as tghui",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-05-29T09:59:08Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000721819,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Ht4",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 10,
        "conditions": "condition_set_1,all,cf_customer_response,in,Yes",
        "actions": "cf_brand,tghui",
        "events": null,
        "display_id": "4ie1y-376",
        "id": 82000721819,
        "impact": 0
    },
    {
        "summary": "If Order Id is 4761234  Add Tag watch",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-02T06:46:05Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000721911,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "lo1",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 11,
        "conditions": "condition_set_1,all,cf_order_id,is,4761234",
        "actions": "add_tag,watch",
        "events": null,
        "display_id": "4ie1y-377",
        "id": 82000721911,
        "impact": 0
    },
    {
        "summary": "If Group is test 28  Add Tag Ht2",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-16T10:39:11Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000722394,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of Copy of ht2",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 13,
        "conditions": "condition_set_1,all,group_id,in,82000660108",
        "actions": "add_tag,Ht2",
        "events": null,
        "display_id": "4ie1y-379",
        "id": 82000722394,
        "impact": 0
    },
    {
        "summary": "If Hour Since first Response Due is 3 AND If Hour Since Agent responded is 2 Set Status as Pending",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-18T02:17:51Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000722445,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of newone",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 14,
        "conditions": "condition_set_1,all,frDueBy,is,3,agent_responded_at,is,2",
        "actions": "cf_status,Pending",
        "events": null,
        "display_id": "4ie1y-380",
        "id": 82000722445,
        "impact": 0
    },
    {
        "summary": "If Ticket Type is Voucher Set Card Status as category 2 And Details as NONE",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-18T08:01:41Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722488,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": "Copy of Copy of ht1",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 16,
        "conditions": "condition_set_1,all,ticket_type,in,Voucher",
        "actions": "cf_card_status,category 2,cf_details,",
        "events": null,
        "display_id": "4ie1y-383",
        "id": 82000722488,
        "impact": 0
    },
    {
        "summary": "If Group is test 9 Set Status as Spares Required",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-24T06:02:04Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000722661,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-24T11:20:01Z",
        "name": " Ht5",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 17,
        "conditions": "condition_set_1,all,group_id,in,82000662461",
        "actions": "cf_status397966,Spares Required",
        "events": null,
        "display_id": "4ie1y-384",
        "id": 82000722661,
        "impact": 0
    },
    {
        "summary": "If Order ID is 1 AND If Group ID is 2 Mark As Spam",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-25T03:56:54Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722710,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:11:46Z",
        "name": "Copy of  Copy 222 of Resolved ticket is checked every hour",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 18,
        "conditions": "condition_set_1,all,cf_order_id822964,is,1,cf_group_id,is,2",
        "actions": "mark_as_spam",
        "events": null,
        "display_id": "4ie1y-385",
        "id": 82000722710,
        "impact": 0
    },
    {
        "summary": "If Order ID is 1 AND If Group ID is 2 Mark As Spam",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-25T04:00:32Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722713,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:11:42Z",
        "name": "Resolved ticket is checked every hour",
        "impactDiffWithDate": "6/25/2025:0,6/26/2025:0,6/27/2025:0",
        "position": 19,
        "conditions": "condition_set_1,all,cf_order_id822964,is,1,cf_group_id,is,2",
        "actions": "mark_as_spam",
        "events": null,
        "display_id": "4ie1y-386",
        "id": 82000722713,
        "impact": 0
    },
    {
        "summary": "If Product is New Knowledge Base Article UI Test  Set Status as Open",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-25T13:52:51Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722744,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:10:33Z",
        "name": "Copy of Copy of b1",
        "impactDiffWithDate": "6/26/2025:0,6/27/2025:0",
        "position": 20,
        "conditions": "condition_set_1,all,product_id,in,82000011880",
        "actions": "status,2",
        "events": null,
        "display_id": "4ie1y-759",
        "id": 82000722744,
        "impact": 0
    },
    {
        "summary": "If Source is bot AND If Status is Waiting for customer  Set Type as Request Product Demo",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-25T13:55:08Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722745,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:11:21Z",
        "name": "Copy of Copy of Copy of h1",
        "impactDiffWithDate": "6/26/2025:0,6/27/2025:0",
        "position": 21,
        "conditions": "condition_set_1,all,source,in,12,status,in,7",
        "actions": "ticket_type,Request Product Demo",
        "events": null,
        "display_id": "4ie1y-760",
        "id": 82000722745,
        "impact": 0
    },
    {
        "summary": "If Source is bot AND If Status is Waiting for customer  Set Type as Request Product Demo",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-25T14:01:39Z",
        "agentName": "Vairavasethupathy B",
        "operator": null,
        "rule_id": 82000722747,
        "affected_tickets_count": 0,
        "last_updated_by": 82175846817,
        "outdated": false,
        "updated_at": "2025-06-25T14:10:25Z",
        "name": "tre",
        "impactDiffWithDate": "6/26/2025:0,6/27/2025:0",
        "position": 22,
        "conditions": "condition_set_1,all,source,in,12,status,in,7",
        "actions": "ticket_type,Request Product Demo",
        "events": null,
        "display_id": "4ie1y-761",
        "id": 82000722747,
        "impact": 0
    },
    {
        "summary": "If Hour Since Agent responded is 1 AND If Hour Since Agent responded is 3 Set Order Id as 1 AND Set Group ID as 2",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-27T05:45:48Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000722802,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-27T05:46:19Z",
        "name": "test",
        "impactDiffWithDate": "6/27/2025:0",
        "position": 23,
        "conditions": "condition_set_1,all,agent_responded_at,is,1,agent_responded_at,is,3",
        "actions": "cf_order_id,1,cf_group_id,2",
        "events": null,
        "display_id": "4ie1y-785",
        "id": 82000722802,
        "impact": 0
    },
    {
        "summary": "If Hour Since Agent responded is 1 AND If Hour Since Agent responded is 3 Set Order Id as 2 AND Set Group ID as 1",
        "automation_type_id": 3,
        "performer": null,
        "active": "true",
        "created_at": "2025-06-27T05:46:45Z",
        "agentName": "Sanjitha S",
        "operator": null,
        "rule_id": 82000722803,
        "affected_tickets_count": 0,
        "last_updated_by": 82175529665,
        "outdated": false,
        "updated_at": "2025-06-27T05:46:49Z",
        "name": "Copy of test",
        "impactDiffWithDate": "6/27/2025:0",
        "position": 24,
        "conditions": "condition_set_1,all,agent_responded_at,is,1,agent_responded_at,is,3",
        "actions": "cf_order_id,2,cf_group_id,1",
        "events": null,
        "display_id": "4ie1y-786",
        "id": 82000722803,
        "impact": 0
    }
]


in this on impactdiffwithdate, how many comma are there 


that many days hasnt active so in table based on the comma count days for each and show active since like with rule name

import React, { useState, useEffect, useRef } from "react";
import { FwSpinner } from "@freshworks/crayons/react";

import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";

const variablePie = require("highcharts/modules/variable-pie");
const variablePieInit =
  typeof variablePie === "function"
    ? variablePie
    : variablePie?.default || (() => {});

variablePieInit(Highcharts);

const funnelModule = require("highcharts/modules/funnel");

const funnelInit =
  typeof funnelModule === "function"
    ? funnelModule
    : funnelModule?.default || (() => {});

funnelInit(Highcharts);
// Initialize the variable pie module

// variablePie(Highcharts);
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  RadialLinearScale,
  LinearScale,
  CategoryScale,
  RadarController,
  LineElement,
  PointElement,
} from "chart.js";
import { Radar } from "react-chartjs-2";

import { PolarArea, Doughnut } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { FunnelController, TrapezoidElement } from "chartjs-chart-funnel";

ChartJS.register(
  ArcElement,
  Tooltip,
  Legend,
  RadialLinearScale,
  LinearScale,
  CategoryScale,
  ChartDataLabels,
  FunnelController,
  TrapezoidElement,
  RadarController,
  LineElement,
  PointElement
);

const NoImpactFunnelChart = ({ noImpactRules }) => {
  if (!noImpactRules || noImpactRules.length === 0)
    return (
      <div 
        style={{
          padding: 20,
          fontStyle: "italic",
          color: "#666",
          textAlign: "center", 
          backgroundColor: "#fafafa",
          borderRadius: 8,
          border: "1px solid #ddd",
          maxWidth: 600,
          margin: "auto",
          boxShadow: "0 2px 5px rgba(0,0,0,0.05)",
        }}
      >
        No No Impact rules to display
      </div>
    );

  const rowHeightPx = 40; 
  const visibleRows = 10;
  
  const getInactiveDays = (impactDiffWithDate) => {
    if (!impactDiffWithDate) return 0;    
    return (impactDiffWithDate.match(/,/g) || []).length;
  };

  return (
    <div
      style={{
        maxWidth: 700,
        margin: "20px auto",
        boxShadow: "0 4px 10px rgba(0,0,0,0.1)",
        borderRadius: 12,
        overflow: "hidden",
        fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
        border: "1px solid #e0e0e0",
      }}
    >
      <div
        style={{
          maxHeight: rowHeightPx * visibleRows,
          overflowY: "auto",
          backgroundColor: "#fff",
        }}
      >
        <table
          style={{
            width: "100%",
            borderCollapse: "separate",
            borderSpacing: 0,
            minWidth: 400,
          }}
        >
          <thead>
            <tr>
              <th
                style={{
                  backgroundColor: "#f5f9ff",
                  color: "#2a3f66",
                  padding: "12px 15px",
                  textAlign: "left",
                  fontWeight: "700",
                  borderBottom: "2px solid #c4d1f5",
                  position: "sticky",
                  top: 0,
                  zIndex: 2,
                  maxWidth: 450,
                }}
              >
                Rule Name
              </th>
              <th
                style={{
                  backgroundColor: "#f5f9ff",
                  color: "#2a3f66",
                  padding: "12px 15px",
                  textAlign: "center",
                  fontWeight: "700",
                  borderBottom: "2px solid #c4d1f5",
                  position: "sticky",
                  top: 0,
                  zIndex: 2,
                  width: 110,
                }}
              >
                Impact
              </th>
            </tr>
          </thead>

          <tbody>
            {noImpactRules.map((rule, idx) => {
              const inactiveDays = getInactiveDays(rule.impactDiffWithDate);
              // Compose tooltip content
              const tooltipContent = `${rule.name || "N/A"}\nInactive for ${inactiveDays} day${inactiveDays !== 1 ? "s" : ""}`;

              return (
                <tr
                  key={rule.id || idx}
                  style={{
                    height: rowHeightPx,
                    backgroundColor: idx % 2 === 0 ? "#fff" : "#f9fbff",
                    transition: "background-color 0.3s ease",
                    cursor: "default",
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = "#d6e4ff";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = idx % 2 === 0 ? "#fff" : "#f9fbff";
                  }}
                >
                  <td
                    style={{
                      borderBottom: "1px solid #e5e9f2",
                      padding: "10px 15px",
                      color: "#2d3a5a",
                      fontSize: 15,
                      fontWeight: "500",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      maxWidth: 450,
                    }}
                    title={tooltipContent}
                  >
                    {rule.name || "N/A"}
                  </td>
                  <td
                    style={{
                      borderBottom: "1px solid #e5e9f2",
                      padding: "10px 15px",
                      textAlign: "center",
                      color: "#4a6dff",
                      fontWeight: "600",
                      fontSize: 15,
                      userSelect: "none",
                    }}
                  >
                    {rule.impact}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const HighImpactColumnChart = ({ rules }) => {
  // Filter out rules with no impact (0, null, undefined)
  // Check if rules is defined and is an array
  if (!rules || !Array.isArray(rules) || rules.length === 0)
    return <div>No High Impact rules to display</div>;

  // Filter out rules with no impact
  const filteredRules = rules.filter(rule => rule.impact > 0);

  if (filteredRules.length === 0)
    return <div>No High Impact rules to display</div>;
  const data = filteredRules.map(rule => ({
    name: rule.name || rule.id || `Rule ${rule.rule_id}`,
    y: rule.impact
  }));

  const totalImpact = filteredRules.reduce((sum, rule) => sum + rule.impact, 0);

  const options = {
    chart: {
      type: 'column',
      height: 400,
    },
    title: { text: '' },
    subtitle: { text: '' },
    xAxis: {
      type: 'category',
      labels: {
        autoRotation: [-45, -90],
        style: {
          fontSize: '13px',
          fontFamily: 'Verdana, sans-serif',
        },
      },
    },
    yAxis: {
      min: 0,
      title: {
        text: 'Impact (tickets affected)',
      },
      labels: {
        formatter: function () {
          return this.value; // Show the actual number without abbreviation
        },
        style: {
          fontSize: '13px',
          fontFamily: 'Verdana, sans-serif',
        },
      },
    },
    legend: { enabled: false },
    tooltip: {
      formatter: function () {
        const percentage = ((this.y / totalImpact) * 100).toFixed(2);
        return `<b>${this.point.name}</b><br/>Impact: <b>${this.y}</b><br/>Percentage: <b>${percentage}%</b>`;
      }
    },
    series: [
      {
        name: 'Impact',
        colorByPoint: true,
        groupPadding: 0,
        data,
        dataLabels: {
          enabled: true,
          color: '#000000',
          verticalAlign: 'bottom',
          inside: false,
          format: '{y}',
          style: {
            fontSize: '13px',
            fontFamily: 'Verdana, sans-serif',
          },
        },
      }
    ],
    colors: [
      '#9b20d9', '#9215ac', '#861ec9', '#7a17e6', '#7010f9', '#691af3',
      '#6225ed', '#5b30e7', '#533be1', '#4c46db', '#4551d5', '#3e5ccf',
      '#3667c9', '#2f72c3', '#277dbd', '#1f88b7', '#1693b1', '#0a9eaa',
      '#03c69b', '#00f194'
    ],
    credits: { enabled: false },
  };

  return <HighchartsReact highcharts={Highcharts} options={options} />;
};

const LowImpactVariablePieChart = ({ rules }) => {
  if (!rules || rules.length === 0) 
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100%",    // or a fixed height like 200px if you want
          fontSize: 18,
          color: "#666",
          minHeight: 150      // or whatever fits your layout
        }}
      >
        No Low Impact rules to display
      </div>
    );

  const data = rules.map((rule) => ({
    name: rule.name || rule.id || `Rule ${rule.rule_id}`,
    y: rule.impact,
    z: rule.impact,  // same value used for radius - modify if you have other metric
  }));

  const colors = [
    '#4caefe',
    '#3dc3e8',
    '#2dd9db',
    '#1feeaf',
    '#0ff3a0',
    '#00e887',
    '#23e274',
    '#a3cb38',
    '#f7b731',
    '#fc5c65'
  ];

  const options = {
    chart: {
      type: 'variablepie',
      height: 400,
    },
    title: {
      text: '',
    },
    tooltip: {
      headerFormat: '',
      pointFormatter: function () {
        return `${this.name}<br/>Impact: <b>${this.y}</b><br/>Percentage: <b>${this.percentage.toFixed(2)}%</b>`;
      }
    },
    
    
    plotOptions: {
      variablepie: {
        dataLabels: {
          enabled: true,
          formatter: function() {
            return `${this.point.percentage.toFixed(1)}%`;
          },
          color: '#000',
          style: {
            fontWeight: 'bold',
            textOutline: 'none'
          }
        }
      }
    },
    series: [{
      minPointSize: 10,
      innerSize: '20%',
      zMin: 0,
      colors,
      name: 'Rules',
      data,
      borderRadius: 5,
    }],
    credits: { enabled: false },
  };

  return <HighchartsReact highcharts={Highcharts} options={options} />;
};


const Workflow_dashboard = ({ client }) => {
  const [timerSeconds, setTimerSeconds] = useState(null);
  const [processingDone, setProcessingDone] = useState(false);
  const [storedvalue1, setStoredvalue1] = useState(null);
  const intervalRef = useRef(null);
  const newRulePloadDB6 = useRef(null);
  const [impactStats, setImpactStats] = useState({});

  const ticketCreate = 1;
  const ticketUpdate = 4;
  const hourlyTriggers = 3;

  const parseImpact = (impactString) => {
    console.log("🔍 Raw impact string:", impactString);
  
    let totalCommaChar_ = (impactString.match(/,/g) || []).length;
    // console.log("🧮 Total comma-separated entries:", totalCommaChar_);
  
    if (totalCommaChar_ > 35) {
      let d = new Date();
      d.setMonth(d.getMonth() - 1);
      let lastDate = d.toLocaleDateString();
      // console.log("📆 Too many entries, splitting from date:", lastDate);
  
      let splitParts = impactString.split(`${lastDate}`);
      // console.log("🧩 After split:", splitParts);
  
      impactString = splitParts[1] || splitParts[0];
      // console.log("✅ Trimmed impact string:", impactString);
    }
  
    const arrStr = impactString.split(/[:,]/).filter((el, i) => i % 2);
    // console.log("🔢 Extracted numeric values:", arrStr);
  
    const total = arrStr.reduce((sum, val) => sum + (parseInt(val) || 0), 0);
    // console.log("🧾 Total impact:", total);
  
    return total;
  };
  

  const analyzeRules = (records, typeLabel) => {
    const activeRules = records.filter((r) => r.active === "true");

    const rulesWithImpact = activeRules.map((r) => {
      const impact = parseImpact(r.impactDiffWithDate || "0:0");
      return { ...r, impact };
    });

    const noImpactRules = rulesWithImpact.filter((r) => r.impact === 0);
    const sortedByImpact = [...rulesWithImpact].sort((a, b) => b.impact - a.impact);
    const top10High = sortedByImpact.slice(0, 10);
    const top10Low = sortedByImpact.filter((r) => r.impact > 0).slice(-10);

    console.log(`🔹 ${typeLabel} ➤ Top 10 Highest Impact Rules (${top10High.length}):`);
    console.log(top10High.map((r) => `${r.name} (${r.impact})`));

    console.log(`🔹 ${typeLabel} ➤ Top 10 Lowest Impact Rules (${top10Low.length}):`);
    console.log(top10Low.map((r) => `${r.name} (${r.impact})`));

    console.log(`🔹 ${typeLabel} ➤ No Impact Rules (${noImpactRules.length})`);
    console.log(noImpactRules);

    return {
      noImpactRules,   //
      topHigh: top10High,
      topLow: top10Low,
    };
  };

  const Filterrecords = async (automationTypeId, dbInstance, typeLabel) => {
    let allRecords = [];
    let nextMarker = null;

    try {
      do {
        const queryObj = { query: { automation_type_id: automationTypeId } };
        if (nextMarker) queryObj.next = { marker: nextMarker };
        const response = await dbInstance.getAll(queryObj);
        if (!response.records || !Array.isArray(response.records)) break;

        const filtered = response.records.map((record) => ({
          ...record.data,
          display_id: record.display_id,
          rule_id: record.data.rule_id,
          automation_type_id: record.data.automation_type_id,
          id: record.data.rule_id || record.data.id,
        }));

        allRecords = allRecords.concat(filtered);
        nextMarker = response.links?.next?.marker || null;
      } while (nextMarker);

      allRecords.sort((a, b) => {
        const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
        const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
        return posA - posB;
      });

    console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
    console.log(`✅ Filtered Records for Type ${automationTypeId}:`, JSON.stringify(allRecords[0], null, 2));

      return analyzeRules(allRecords, typeLabel);
    } catch (error) {
      console.error("❌ Error fetching filtered records:", error);
      return { noImpactCount: 0, topHigh: [], topLow: [], topDuplicates: [] };
    }
  };

  const handleFilterRecords = async () => {
    const dbInstance = newRulePloadDB6.current;
    if (!dbInstance) return;

    const creationStats = await Filterrecords(ticketCreate, dbInstance, "Create");
    const updateStats = await Filterrecords(ticketUpdate, dbInstance, "Update");
    const hourlyStats = await Filterrecords(hourlyTriggers, dbInstance, "Hourly");

    setImpactStats({ create: creationStats, update: updateStats, hourly: hourlyStats });
  };

  useEffect(() => {
    const initDB = async () => {
      try {
        const entity = await client.db.entity({ version: "v1" });
        newRulePloadDB6.current = entity.get("newRulePloadDB6");
      } catch (error) {
        console.error("Failed to init DB:", error);
      }
    };
    initDB();
  }, [client]);

  useEffect(() => {
    const fetchStored = async () => {
      try {
        const val = await client.db.get("RulesDB");
        setStoredvalue1(val);
      } catch (err) {
        console.error("Error fetching RulesDB:", err);
        setStoredvalue1(null);
      }
    };
    fetchStored();
    const interval = setInterval(fetchStored, 60000);
    return () => clearInterval(interval);
  }, [client]);

  useEffect(() => {
    if (!storedvalue1) return;
    const itemsPerPage = 100;
    const secondsPerPage = 60;
    const fixedOverhead = 60;

    const getTime = (count) =>
      count > 0 ? Math.ceil(count / itemsPerPage) * secondsPerPage + fixedOverhead : 0;

    const creationTime = getTime(storedvalue1.creationTotal || 0);
    const hourlyTime = getTime(storedvalue1.hourlyTotal || 0);
    const updateTime = getTime(storedvalue1.updateTotal || 0);
    const totalTime = creationTime + hourlyTime + updateTime;

    if (totalTime <= 0) {
      setTimerSeconds(null);
      setProcessingDone(true);
      return;
    }

    setTimerSeconds(totalTime);
    setProcessingDone(false);
    let remaining = totalTime;

    if (intervalRef.current) clearInterval(intervalRef.current);

    intervalRef.current = setInterval(() => {
      remaining -= 1;
      setTimerSeconds(remaining);
      if (remaining <= 0) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
        setTimerSeconds(0);
        setProcessingDone(true);
      }
    }, 1000);

    return () => clearInterval(intervalRef.current);
  }, [storedvalue1]);

  useEffect(() => {
    if (processingDone && newRulePloadDB6.current) {
      handleFilterRecords();
    }
  }, [processingDone, newRulePloadDB6.current]);

 

return (
  <div>
    {!processingDone ? (
      <div
        style={{
          backgroundColor: "#f0f0f0",
          height: "100vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            backgroundColor: "white",
            padding: "20px 30px",
            borderRadius: 8,
            fontSize: 18,
            userSelect: "none",
          }}
        >
          <FwSpinner size="small" color="green" style={{ marginRight: 8 }} />
          <div>
            Processing data. Please revisit in (<strong>{timerSeconds}</strong>) seconds.
          </div>
        </div>
      </div>
    ) : (
      <div style={{ backgroundColor: "#fff", minHeight: "100vh" }}>
        <h1>🎉 Dashboard Ready</h1>

        {/* Render each rule individually so you can add separate styling */}
        {["create", "update", "hourly"].map((key) => (
          // You now have control over outer div for each rule
          <div
            key={key}
            style={{
              // marginBottom: 40,
              backgroundColor: "#f4f4f48c", // brown card
              padding: 20,
              color: "black",
              // You can add more custom styles here per rule if you want
            }}
          >
            <h2 style={{ marginBottom: 20 }}>{key.toUpperCase()} Rules</h2>

            {/* Wrap the 3 charts for this rule in their own container */}
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                gap: 20,
                flexWrap: "wrap",
                // You can add extra styling here that applies only to this div
              }}
            >
              <div
                style={{
                  flex: "1",
                  maxWidth: 500,
                  backgroundColor: "#fff",
                  // borderRadius: 10,
                  padding: 10,
                  color: "#000",
                }}
              >
                <h4>🎯 Top 10 High Impact</h4>
                <HighImpactColumnChart rules={impactStats[key]?.topHigh} />
              </div>

              <div
                style={{
                  flex: "1",
                  maxWidth: 500,
                  backgroundColor: "#fff",
                  // borderRadius: 10,
                  padding: 10,
                  color: "#000",
                }}
              >
                <h4>📡 Top 10 Low Impact</h4>
                <LowImpactVariablePieChart rules={impactStats[key]?.topLow} />
              </div>

              <div
                style={{
                  flex: "1",
                  maxWidth: 500,
                  backgroundColor: "#fff",
                  // borderRadius: 10,
                  padding: 10,
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "space-between",
                  color: "#000",
                }}
              >
                <h4>🚫 No Impact</h4>
                <div
                  style={{
                    height: 400,
                    maxWidth: 500,
                    backgroundColor: "#fff",
                    borderRadius: 10,
                    padding: 10,
                  }}
                >
                  <NoImpactFunnelChart noImpactRules={impactStats[key]?.noImpactRules} />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    )}
  </div>
);

};

export default Workflow_dashboard;