import React from "react";
import {
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  Legend,
  ResponsiveContainer,
  Tooltip,
} from "recharts";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import "../styles/RpnRadarChart.css";

/**
 * RPN dimensions: Likelihood vs Severity (from answers / RPN config).
 */
const RpnRadarChart = ({ data, widgetId }) => {
  const maxValue = React.useMemo(() => {
    if (!data?.length) return 10;
    let m = 0;
    data.forEach((d) => {
      if (typeof d.likelihood === "number") m = Math.max(m, d.likelihood);
      if (typeof d.severity === "number") m = Math.max(m, d.severity);
    });
    return m > 0 ? Math.min(20, Math.ceil(m / 2) * 2 || 10) : 10;
  }, [data]);

  const tooltipFormatter = (value, name, item) => {
    const dataKey = item?.dataKey ?? name;
    const label =
      dataKey === "likelihood" || (typeof name === "string" && name.toLowerCase().includes("likelihood"))
        ? "Likelihood of harm"
        : "Severity of harm";
    const scaleNote = `(scale 0–${maxValue})`;
    return [`${value} ${scaleNote}`, label];
  };

  return (
    <div className="rpn-radar-container chart-card chart-card--has-add-btn" tabIndex={-1}>
      {widgetId && <AddToPersonalizedButton widgetId={widgetId} />}
      <h2 className="rpn-radar-title">RPN: Likelihood vs Severity by Category</h2>
      <p className="chart-subtitle">
        <strong>In short:</strong> Blue = likelihood of harm; orange = severity of harm. Scale adapts to data (e.g. 0–10). Each axis is a risk category. Larger shape = higher risk. Hover to see exact values.
      </p>
      <ResponsiveContainer width="100%" height={280}>
        <RadarChart cx="50%" cy="50%" outerRadius="70%" data={data}>
          <PolarGrid stroke="#e5e5e5" />
          <PolarAngleAxis
            dataKey="subject"
            tick={{ fontSize: 11, fill: "var(--text-secondary, #4d4d4f)" }}
          />
          <PolarRadiusAxis
            angle={30}
            domain={[0, maxValue]}
            tick={{ fontSize: 10, fill: "var(--text-muted, #999)" }}
            tickFormatter={(v) => `${v}`}
          />
          <Radar
            name="Likelihood of harm"
            dataKey="likelihood"
            stroke="#2196f3"
            fill="#2196f3"
            fillOpacity={0.35}
            strokeWidth={2}
          />
          <Radar
            name="Severity of harm"
            dataKey="severity"
            stroke="#f21b23"
            fill="#f21b23"
            fillOpacity={0.35}
            strokeWidth={2}
          />
          <Legend
            verticalAlign="bottom"
            height={36}
            wrapperStyle={{ fontSize: "0.8rem" }}
          />
          <Tooltip
            formatter={tooltipFormatter}
            contentStyle={{
              borderRadius: "8px",
              border: "1px solid #e5e5e5",
              boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
            }}
          />
        </RadarChart>
      </ResponsiveContainer>
    </div>
  );
};

export default RpnRadarChart;
