import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';

function BucketPieTooltip({ active, payload, total }) {
  if (!active || !payload?.length) return null;
  const p = payload[0]?.payload;
  if (!p) return null;
  const pct = total > 0 ? Math.round((p.value / total) * 100) : 0;
  return (
    <div className="ex-dash-pie-tooltip">
      <strong className="ex-dash-pie-tooltip-title">{p.title}</strong>
      <span className="ex-dash-pie-tooltip-count">
        <span className="ex-dash-pie-tooltip-num">{p.value}</span>
        <span className="ex-dash-pie-tooltip-pct">{pct}%</span>
      </span>
      <p className="ex-dash-pie-tooltip-hint">{p.hint}</p>
    </div>
  );
}

/**
 * Donut chart + legend mirroring metric card titles, hints, and counts.
 *
 * @param {object} props
 * @param {'executor'|'verifier'} props.role
 * @param {string} [props.heading] — section title
 * @param {number} props.total — assignment count for this role
 * @param {{ category: string, title: string, hint: string, value: number, fill: string }[]} props.segments
 * @param {(category: string) => void} [props.onSegmentClick]
 */
export default function DashboardBucketPieChart({
  role,
  heading = 'Status distribution',
  total,
  segments,
  onSegmentClick
}) {
  const pieData = segments.filter((s) => s.value > 0);

  if (total <= 0) {
    return (
      <div className={`ex-dash-bucket-pie ex-dash-bucket-pie--empty ex-dash-bucket-pie--role-${role}`}>
        <p className="ex-dash-bucket-pie-empty-msg">
          No assignments yet — status distribution will appear here.
        </p>
      </div>
    );
  }

  return (
    <div className={`ex-dash-bucket-pie ex-dash-bucket-pie--role-${role}`}>
      <div className="ex-dash-bucket-pie-head">
        <div className="ex-dash-bucket-pie-head-text">
          <span className="ex-dash-bucket-pie-title">{heading}</span>
          <p className="ex-dash-bucket-pie-lede">Click a segment or row to open that bucket.</p>
        </div>
        <span className="ex-dash-bucket-pie-sub">{total} total</span>
      </div>
      <div className="ex-dash-bucket-pie-body">
        <div className="ex-dash-bucket-pie-chart-wrap ex-dash-pie-donut-stage">
          {pieData.length > 0 ? (
            <>
              <div className="ex-dash-pie-donut-ring" aria-hidden />
              <ResponsiveContainer width="100%" height={268}>
                <PieChart margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
                  <Pie
                    data={pieData}
                    dataKey="value"
                    nameKey="title"
                    cx="50%"
                    cy="50%"
                    innerRadius="52%"
                    outerRadius="88%"
                    paddingAngle={3}
                    cornerRadius={6}
                    stroke="none"
                    label={false}
                    onClick={(_, index) => {
                      const d = pieData[index];
                      if (d?.category) onSegmentClick?.(d.category);
                    }}
                    cursor="pointer"
                    animationBegin={80}
                    animationDuration={520}
                    animationEasing="ease-out"
                  >
                    {pieData.map((entry) => (
                      <Cell
                        key={entry.category}
                        fill={entry.fill}
                        stroke="#ffffff"
                        strokeWidth={3}
                        className="ex-dash-pie-cell"
                      />
                    ))}
                  </Pie>
                  <Tooltip
                    content={<BucketPieTooltip total={total} />}
                    wrapperStyle={{ zIndex: 10, outline: 'none' }}
                  />
                </PieChart>
              </ResponsiveContainer>
              <div className="ex-dash-pie-center" aria-hidden>
                <span className="ex-dash-pie-center-value">{total}</span>
                <span className="ex-dash-pie-center-label">assignments</span>
              </div>
            </>
          ) : (
            <div className="ex-dash-bucket-pie-chart-fallback" role="status">
              No bucket counts to chart
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
