import React from "react";
import { useNavigate } from "react-router-dom";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import "../styles/RpnAuditBarChart.css";

const RPN_VALUES = [1, 2, 4, 8, 16, 32, 64, 128];

/* Low RPN (1,2,4…) → high RPN (128): cool/safe to warm/critical */
const BAR_GRADIENTS = [
  { id: "rpn1", start: "#34d399", end: "#10b981" },   /* emerald */
  { id: "rpn2", start: "#38bdf8", end: "#0ea5e9" },   /* sky blue */
  { id: "rpn3", start: "#a78bfa", end: "#8b5cf6" },   /* violet */
  { id: "rpn4", start: "#e879f9", end: "#d946ef" },   /* fuchsia */
  { id: "rpn5", start: "#fbbf24", end: "#f59e0b" },   /* amber */
  { id: "rpn6", start: "#fb923c", end: "#f97316" },   /* orange */
  { id: "rpn7", start: "#f87171", end: "#f21b23" },  /* red (SAT brand) */
  { id: "rpn8", start: "#dc2626", end: "#b91c1c" },  /* deep red */
];

const CustomTooltip = ({ active, payload, label }) => {
  if (!active || !payload?.length) return null;
  const value = payload[0]?.value ?? 0;
  return (
    <div className="rpn-audit-tooltip">
      <div className="rpn-audit-tooltip-label">RPN {label}</div>
      <div className="rpn-audit-tooltip-value">
        {value} audit{value !== 1 ? "s" : ""}
      </div>
      <div className="rpn-audit-tooltip-hint">Click to view list</div>
    </div>
  );
};

const RpnAuditBarChart = ({ data }) => {
  const navigate = useNavigate();
  const chartData = (data && data.length)
    ? data
    : RPN_VALUES.map((v) => ({ name: String(v), rpnValue: v, count: 0 }));

  const handleBarClick = (ev) => {
    const entry = ev?.payload;
    if (entry && (entry.rpnValue != null || entry.name != null)) {
      const value = entry.rpnValue != null ? entry.rpnValue : Number(entry.name);
      if (!Number.isNaN(value)) {
        navigate(`/dashboard/rpn-audit-list/${value}`);
      }
    }
  };

  return (
    <div
      className="rpn-audit-bar-container chart-card chart-card--has-add-btn rpn-audit-bar-premium"
      role="region"
      aria-label="RPN audit count bar chart"
    >
      <AddToPersonalizedButton widgetId="rpnAuditBar" />
      <div className="rpn-audit-bar-header">
        <div className="rpn-audit-bar-title-wrap">
          <span className="rpn-audit-bar-icon" aria-hidden>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M3 3v18h18" />
              <path d="M7 16v-5h4v5" />
              <path d="M12 16V9h4v7" />
              <path d="M17 16v-3h4v3" />
            </svg>
          </span>
          <h2 className="rpn-audit-bar-title">Audits by RPN Value</h2>
        </div>
        <p className="rpn-audit-bar-subtitle">
          Based on total RPN (sum of all RPN answers in each audit). Bars = 1, 2, 4, 8, 16, 32, 64, 128 (total in range). Each audit counted once. Click a bar to see the list.
        </p>
      </div>
      <div className="rpn-audit-bar-chart-wrap">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart
            data={chartData}
            margin={{ top: 20, right: 24, left: 12, bottom: 16 }}
          >
            <defs>
              {BAR_GRADIENTS.map((g, i) => (
                <linearGradient key={g.id} id={g.id} x1="0" y1="1" x2="0" y2="0">
                  <stop offset="0%" stopColor={g.end} />
                  <stop offset="100%" stopColor={g.start} />
                </linearGradient>
              ))}
            </defs>
            <CartesianGrid
              strokeDasharray="0"
              stroke="rgba(0,0,0,0.06)"
              vertical={false}
              horizontal={true}
            />
            <XAxis
              dataKey="name"
              tick={{ fontSize: 13, fontWeight: 600, fill: "var(--rpn-axis, #475569)" }}
              axisLine={{ stroke: "var(--rpn-axis-line, #e2e8f0)", strokeWidth: 1.5 }}
              tickLine={false}
              tickMargin={10}
            />
            <YAxis
              type="number"
              tick={{ fontSize: 12, fill: "var(--rpn-axis, #64748b)" }}
              axisLine={false}
              tickLine={false}
              allowDecimals={false}
              tickMargin={8}
              width={32}
            />
            <Tooltip
              content={<CustomTooltip />}
              cursor={{ fill: "rgba(15, 23, 42, 0.04)", radius: 6 }}
            />
            <Bar
              dataKey="count"
              name="Audits"
              radius={[8, 8, 0, 0]}
              maxBarSize={48}
              onClick={(payload) => handleBarClick(payload)}
              cursor="pointer"
            >
              {chartData.map((entry, index) => (
                <Cell
                  key={`cell-${entry.rpnValue ?? entry.name}`}
                  fill={`url(#${BAR_GRADIENTS[index % BAR_GRADIENTS.length].id})`}
                  className="rpn-audit-bar-cell"
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default RpnAuditBarChart;
