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

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 ImpactPolarChart = ({ rules }) => {
  if (!rules || rules.length === 0) return null;

  const labels = rules.map((r) => r.name || r.id || `Rule ${r.rule_id}`);
  const dataValues = rules.map((r) => r.impact);
  const total = dataValues.reduce((a, b) => a + b, 0);

  const data = {
    labels,
    datasets: [
      {
        label: "",
        data: dataValues,
        backgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56",
          "#4BC0C0",
          "#9966FF",
          "#FF9F40",
          "#C9CBCF",
          "#A3CB38",
          "#FDA7DC",
          "#C4E538",
        ],
        borderWidth: 1,
      },
    ],
  };

  const options = {
    plugins: {
      legend: { display: false },
      datalabels: {
        color: "#000",
        formatter: (value) => {
          const percent = ((value / total) * 100).toFixed(1);
          return `${percent}%`;
        },
        font: {
          weight: "bold",
        },
      },
      tooltip: {
        callbacks: {
          label: function (context) {
            // const label = context.label || "";
            const val = context.raw;
            const percent = ((val / total) * 100).toFixed(1);
            return `${val} tickets affected (${percent}%)`;
          },
        },
      },
    },
  };

  return <PolarArea data={data} options={options} plugins={[ChartDataLabels]} />;
};

const LowImpactRadarChart = ({ rules }) => {
  if (!rules || rules.length === 0) return null;

  const labels = rules.map((r) => r.name || r.id || `Rule ${r.rule_id}`);
  const dataValues = rules.map((r) => r.impact);
  const total = dataValues.reduce((a, b) => a + b, 0);

  const data = {
    labels,
    datasets: [
      {
        label: "Impact",
        data: dataValues,
        backgroundColor: "rgba(54, 162, 235, 0.2)",
        borderColor: "rgba(54, 162, 235, 1)",
        pointBackgroundColor: "rgba(54, 162, 235, 1)",
        borderWidth: 2,
      },
    ],
  };

  const options = {
    responsive: true,
    scales: {
      r: {
        pointLabels: {
          display: false, // ✅ Hides the outer labels on chart
        },
        ticks: {
          backdropColor: 'transparent', // Optional: makes it cleaner
        },
      },
    },
    plugins: {
      legend: { display: false },
      tooltip: {
        callbacks: {
          label: function (context) {
            // const label = context.label || "";
            const val = context.raw;
            const percent = ((val / total) * 100).toFixed(1);
            return `${val} tickets affected (${percent}%)`;
          },
        },
      },
    },
  };

  return <Radar data={data} 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 {
      noImpactCount: noImpactRules.length,
      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>
  
          {["create", "update", "hourly"].map((key) => (
            <div
              key={key}
              style={{
                marginBottom: 40,
                backgroundColor: "#e7e7e78c", // brown card
                // borderRadius: 12,
                padding: 20,
                color: "white",
              }}
            >
              <h2 style={{ marginBottom: 20 }}>🧠 {key.toUpperCase()} Rules</h2>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  gap: 20,
                  flexWrap: "wrap",
                }}
              >
                <div
                  style={{
                    flex: "1",
                    maxWidth: 500,
                    backgroundColor: "#fff",
                    borderRadius: 10,
                    padding: 10,
                    color: "#000",
                  }}
                >
                  <h4>🎯 Top 10 High Impact</h4>
                  <ImpactPolarChart 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>
<LowImpactRadarChart 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: 220,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      border: "1px solid #ccc",
                      borderRadius: 8,
                      backgroundColor: "#f9f9f9",
                      fontWeight: "bold",
                      fontSize: 20,
                    }}
                  >
                    {impactStats[key]?.noImpactCount ?? 0}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
  
  
};

export default Workflow_dashboard;





in this, for top 10 low, use this chart


// Data retrieved from https://worldpopulationreview.com/country-rankings/countries-by-density
Highcharts.chart('container', {
    chart: {
        type: 'variablepie'
    },
    title: {
        text: 'Countries compared by population density and total area, 2024'
    },
    tooltip: {
        headerFormat: '',
        pointFormat: '<span style="color:{point.color}">\u25CF</span> <b> ' +
            '{point.name}</b><br/>' +
            'Area (square km): <b>{point.y}</b><br/>' +
            'Population density (people per square km): <b>{point.z}</b><br/>'
    },
    series: [{
        minPointSize: 10,
        innerSize: '20%',
        zMin: 0,
        name: 'countries',
        borderRadius: 5,
        data: [{
            name: 'Spain',
            y: 505992,
            z: 95
        }, {
            name: 'France',
            y: 551695,
            z: 118
        }, {
            name: 'Poland',
            y: 312679,
            z: 131
        }, {
            name: 'Czech Republic',
            y: 78865,
            z: 136
        }, {
            name: 'Italy',
            y: 301336,
            z: 198
        }, {
            name: 'Switzerland',
            y: 41284,
            z: 224
        }, {
            name: 'Germany',
            y: 357114,
            z: 238
        }],
        colors: [
            '#4caefe',
            '#3dc3e8',
            '#2dd9db',
            '#1feeaf',
            '#0ff3a0',
            '#00e887',
            '#23e274'
        ]
    }]
});

#container {
    height: 500px;
}

.highcharts-figure,
.highcharts-data-table table {
    min-width: 320px;
    max-width: 700px;
    margin: 1em auto;
}

.highcharts-data-table table {
    font-family: Verdana, sans-serif;
    border-collapse: collapse;
    border: 1px solid #ebebeb;
    margin: 10px auto;
    text-align: center;
    width: 100%;
    max-width: 500px;
}

.highcharts-data-table caption {
    padding: 1em 0;
    font-size: 1.2em;
    color: #555;
}

.highcharts-data-table th {
    font-weight: 600;
    padding: 0.5em;
}

.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
    padding: 0.5em;
}

.highcharts-data-table thead tr,
.highcharts-data-table tbody tr:nth-child(even) {
    background: #f8f8f8;
}

.highcharts-data-table tr:hover {
    background: #f1f7ff;
}

.highcharts-description {
    margin: 0.3rem 10px;
}


<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/variable-pie.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
    <p class="highcharts-description">
        Variable radius pie charts can be used to visualize a
        second dimension in a pie chart. In this chart, the more
        densely populated countries are drawn further out, while the
        slice width is determined by the size of the country.
    </p>
</figure>



react js