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 }) => {

  console.log("New No Impact at 6.48pm");

  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;

  // Limit rules to first 10 only
  const displayRules = noImpactRules.slice(0, 10);

  // Count commas and add 1 to get days in impactDiffWithDate
  const getInactiveDays = (impactDiffWithDate) => {
    if (!impactDiffWithDate) return 0;
    return (impactDiffWithDate.match(/,/g) || []).length + 1;
  };

  return (
    <>
      <style>{`
        /* Remove scroll-container max-height and overflow */
        .scroll-container {
          font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
          border-radius: 12px;
          background-color: #fff;
        }
      `}</style>

      <div
        style={{
          maxWidth: 700,
          overflow: "hidden",
          fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
        }}
      >
        <div className="scroll-container">
          <table
            style={{
              width: "100%",
              borderCollapse: "separate",
              borderSpacing: 0,
              minWidth: 500,
              // allow table to expand naturally (no fixed height or max height)
            }}
          >
            <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: 100,
                    whiteSpace: "nowrap",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                  }}
                >
                  Rule Name
                </th>
                <th
                  style={{
                    backgroundColor: "#f5f9ff",
                    color: "#2a3f66",
                    padding: "12px 40px",
                    textAlign: "center",
                    fontWeight: "700",
                    borderBottom: "2px solid #c4d1f5",
                    position: "sticky",
                    top: 0,
                    zIndex: 2,
                    width: 120,
                  }}
                >
                  Days Inactive
                </th>
              </tr>
            </thead>

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

    return (
      <tr
        key={rule.id || idx}
        style={{
          height: 28, 
          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: "6px 10px",  // reduced padding
            color: "#2d3a5a",
            fontSize: 15,
            fontWeight: "500",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
            maxWidth: 300,
          }}
          title={tooltipContent}
        >
          {rule.name || "N/A"}
        </td>
        <td
          style={{
            borderBottom: "1px solid #e5e9f2",
            padding: "6px 10px",  // reduced padding
            textAlign: "center",
            color: "#4a6dff",
            fontWeight: "600",
            fontSize: 13,
            userSelect: "none",
          }}
          title={tooltipContent}
        >
          {inactiveDays}
        </td>
      </tr>
    );
  })}
</tbody>
          </table>
        </div>
      </div>
    </>
  );
};

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

  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: 300,
    },
    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 LoadingWrapper = ({ loading, children }) => {
  if (loading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: 340, 
          marginLeft:-50
        }}
      >
        <FwSpinner size="medium" color="green" label="Loading..." />
      </div>
    );
  }
  return children;
};

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) => {
  const stats = impactStats[key];
  const isLoading = !stats; // if stats object is null/undefined – treat as loading

  return (
    <div key={key} style={{ /* your existing styles */ }}>
      <h2 style={{ marginBottom: 20 }}>{key.toUpperCase()} Rules</h2>

      <div style={{
        display: "flex",
        justifyContent: "space-between",
        backgroundColor: "#f4f4f48c", // brown card
        padding: 20,
        gap: 20,
        flexWrap: "wrap",
      }}>
        <div style={{ flex: "1", maxWidth: 500, backgroundColor: "#fff", padding: 10, color: "#000" }}>
          <h4>🎯 Top 10 High Impact</h4>
          <LoadingWrapper loading={isLoading}>
            <HighImpactColumnChart rules={stats?.topHigh || []} />
          </LoadingWrapper>
        </div>

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

        <div style={{
          flex: "1",
          maxWidth: 500,
          backgroundColor: "#fff",
          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 }}>
            <LoadingWrapper loading={isLoading}>
              <NoImpactFunnelChart noImpactRules={stats?.noImpactRules || []} />
            </LoadingWrapper>
          </div>
        </div>
      </div>
    </div>
  );
})}
      </div>
    )}
  </div>
);

};

export default Workflow_dashboard;



in this on filtering, will i use active = true or not