import React from "react";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
} from "recharts";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import "../styles/RpnDistributionChart.css";

/**
 * RPN (Risk Priority Number) distribution from answers.
 * Shows Low / Medium / High RPN bands based on answer-derived values.
 */
const RpnDistributionChart = ({ data, widgetId }) => {
  const COLORS = ["#4caf50", "#f21b23", "#f44336"];
  const RADIAN = Math.PI / 180;
  const renderCustomizedLabel = ({
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    percent,
  }) => {
    const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);
    if (percent < 0.05) return null;
    return (
      <text
        x={x}
        y={y}
        fill="white"
        textAnchor="middle"
        dominantBaseline="central"
        className="rpn-pie-label"
      >
        {`${(percent * 100).toFixed(0)}%`}
      </text>
    );
  };

  const total = data.reduce((sum, d) => sum + d.value, 0) || 1;
  const tooltipFormatter = (value, name) => {
    const pct = total ? ((value / total) * 100).toFixed(1) : "0";
    return [`${value} answers (${pct}%)`, name];
  };

  return (
    <div className="rpn-distribution-container chart-card chart-card--has-add-btn" tabIndex={-1}>
      {widgetId && <AddToPersonalizedButton widgetId={widgetId} />}
      <h2 className="rpn-distribution-title">Risk Priority Number (RPN) Distribution</h2>
      <p className="chart-subtitle">
        <strong>In short:</strong> Number of answers in each RPN risk band: green = low risk (1–25), orange = medium (26–80), red = high (81–125). Hover a slice for the exact count and percentage.
      </p>
      <ResponsiveContainer width="100%" height={280}>
        <PieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            labelLine={false}
            label={renderCustomizedLabel}
            outerRadius={90}
            innerRadius={50}
            dataKey="value"
            nameKey="name"
          >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
            ))}
          </Pie>
          <Tooltip
            formatter={tooltipFormatter}
            contentStyle={{
              borderRadius: "8px",
              border: "1px solid #e5e5e5",
              boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
            }}
          />
          <Legend
            verticalAlign="bottom"
            height={36}
            formatter={(value, entry) => (
              <span className="rpn-legend-item">
                <span
                  className="rpn-legend-dot"
                  style={{ background: entry.color }}
                />
                {value}
              </span>
            )}
          />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
};

export default RpnDistributionChart;
