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 = ({ noImpactCount }) => {
  if (!noImpactCount || noImpactCount === 0) 
    return <div>No No Impact rules to display</div>;
  
  const data = [
    ['No Impact Rules', noImpactCount]
  ];

  const options = {
    chart: {
      type: 'funnel',
      height: 400,
    },
    title: {
      text: 'No Impact Rules Funnel',
    },
    plotOptions: {
      series: {
        dataLabels: {
          enabled: true,
          format: '<b>{point.name}</b> ({point.y})',
          softConnector: true,
          color: '#000',
        },
        center: ['40%', '50%'],
        neckWidth: '30%',
        neckHeight: '25%',
        width: '80%',
      }
    },
    legend: { enabled: false },
    series: [{
      name: 'Rules',
      data,
    }],
    credits: {
      enabled: false,
    },
    responsive: {
      rules: [{
        condition: { maxWidth: 500 },
        chartOptions: {
          plotOptions: {
            series: {
              dataLabels: { inside: true },
              center: ['50%', '50%'],
              width: '100%',
            },
          },
        },
      }],
    },
  };

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


const HighImpactColumnChart = ({ rules }) => {
  if (!rules || rules.length === 0)
    return <div>No High Impact rules to display</div>;

  // Map rules to Highcharts format [ [name, value], ... ]
  const data = rules.map(rule => [
    rule.name || rule.id || `Rule ${rule.rule_id}`,
    rule.impact
  ]);

  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)',
      },
    },
    legend: { enabled: false },
    tooltip: {
      pointFormat: 'Impact: <b>{point.y}</b>'
    },
    series: [
      {
        name: 'Impact',
        colorByPoint: true,
        groupPadding: 0,
        data,
        dataLabels: {
          enabled: true,
          rotation: -90,
          color: '#FFFFFF',
          inside: true,
          verticalAlign: 'top',
          format: '{point.y:.0f}', // whole number
          y: 10,
          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 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 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: '',
      pointFormat:
        `<span style="color:{point.color}">\u25CF</span> <b>{point.name}</b><br/>` +
        `Impact (size): <b>{point.y}</b><br/>` +
        `Impact (radius): <b>{point.z}</b><br/>`
    },
    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 {
      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>
//   <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 noImpactCount={impactStats[key]?.noImpactCount} />
// </div>
//                 </div>
//               </div>
//             </div>
//           ))}
//         </div>
//       )}
//     </div>
//   );
  
  

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 noImpactCount={impactStats[key]?.noImpactCount} />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    )}
  </div>
);

};

export default Workflow_dashboard;


in this code, after filtering records, what will happen?