import React from "react";
import { useNavigate } from "react-router-dom";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
} from "recharts";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import "../styles/HarmPieChart.css";

/** Likelihood of harm categories: Probable, Likely, Possible, Remote */
const LIKELIHOOD_COLORS = ["#7c3aed", "#2563eb", "#0891b2", "#0d9488"];

const LikelihoodOfHarmPieChart = ({ data }) => {
  const navigate = useNavigate();
  const RADIAN = Math.PI / 180;
  const renderLabel = ({
    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="harm-pie-label"
      >
        {`${(percent * 100).toFixed(0)}%`}
      </text>
    );
  };

  const safeData = data && data.length ? data : [];
  const total = safeData.reduce((sum, d) => sum + (d.value || 0), 0);
  const hasResponses = total > 0;
  const chartData = hasResponses
    ? safeData
    : [{ name: "No responses yet", value: 1 }];

  const tooltipFormatter = (value, name) => {
    if (!hasResponses) return [value, name];
    const pct = total ? (((value || 0) / total) * 100).toFixed(1) : "0";
    return [`${value} (${pct}%)`, name];
  };

  const handleSegmentClick = (entry) => {
    if (!entry || !hasResponses) return;
    if (entry.name === "No responses yet") return;
    navigate(`/dashboard/likelihood-of-harm-stats?segment=${encodeURIComponent(entry.name)}`);
  };

  const handleContainerClick = () => {
    navigate("/dashboard/likelihood-of-harm-stats");
  };

  return (
    <div
      className="harm-pie-container chart-card chart-card--has-add-btn"
      onClick={handleContainerClick}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          navigate("/dashboard/likelihood-of-harm-stats");
        }
      }}
      role={hasResponses ? undefined : "button"}
      tabIndex={hasResponses ? undefined : 0}
      aria-label="View Likelihood of Harm detailed statistics"
    >
      <AddToPersonalizedButton widgetId="likelihoodOfHarm" />
      <h2 className="harm-pie-title">Likelihood of Harm</h2>
      <p className="harm-pie-subtitle">
        {hasResponses ? "Click a segment to view that category, or the chart to view all" : "Submit observations with a “Likelihood of harm” question to see distribution."}
      </p>
      <ResponsiveContainer width="100%" height={280}>
        <PieChart>
          <Pie
            data={chartData}
            cx="50%"
            cy="50%"
            labelLine={false}
            label={hasResponses ? renderLabel : undefined}
            outerRadius={90}
            innerRadius={50}
            dataKey="value"
            nameKey="name"
            onClick={(data, index, evt) => {
              evt?.stopPropagation?.();
              handleSegmentClick(chartData[index]);
            }}
            style={{ cursor: hasResponses ? "pointer" : "default" }}
          >
            {chartData.map((entry, index) => (
              <Cell
                key={`cell-${index}`}
                fill={
                  hasResponses
                    ? LIKELIHOOD_COLORS[index % LIKELIHOOD_COLORS.length]
                    : "#e5e7eb"
                }
                style={{ cursor: hasResponses ? "pointer" : "default" }}
              />
            ))}
          </Pie>
          <Tooltip
            formatter={tooltipFormatter}
            contentStyle={{
              borderRadius: "8px",
              border: "1px solid #e0e0e0",
              boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
            }}
          />
          <Legend
            verticalAlign="bottom"
            height={36}
            formatter={(value, entry) => (
              <span className="harm-legend-item">
                <span
                  className="harm-legend-dot"
                  style={{ background: entry.color }}
                />
                {value}
              </span>
            )}
          />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
};

export default LikelihoodOfHarmPieChart;
