import React, { useEffect, useMemo, useRef, useState } from "react";
import { chartScaleMax, handleDashboardActivate } from "../../utils/dashboardHelpers.js";

const DEFAULT_WIDTH = 640;
const MIN_WIDTH = 280;
const HEIGHT = 260;
const PAD = { top: 16, right: 16, bottom: 48, left: 44 };

function formatAxisLabel(label, slotWidth) {
  if (slotWidth >= 72 || label.length <= 10) return label;
  return label.length > 12 ? `${label.slice(0, 11)}…` : label;
}

export default function PermitBarChart({
  data = [],
  title,
  description,
  emptyMessage = "No data for this period.",
  accentColor = "var(--portal-accent, #c41e2d)",
  onClick,
  onBarClick
}) {
  const canvasRef = useRef(null);
  const [chartWidth, setChartWidth] = useState(DEFAULT_WIDTH);
  const clickable = Boolean(onClick || onBarClick);

  useEffect(() => {
    const node = canvasRef.current;
    if (!node) return undefined;
    const updateWidth = () => {
      const nextWidth = Math.round(node.getBoundingClientRect().width);
      if (nextWidth > 0) setChartWidth(Math.max(MIN_WIDTH, nextWidth));
    };
    updateWidth();
    const observer = new ResizeObserver(updateWidth);
    observer.observe(node);
    return () => observer.disconnect();
  }, []);

  const maxValue = useMemo(() => {
    const peak = Math.max(0, ...data.map((item) => Number(item.value ?? item.count) || 0));
    return chartScaleMax(peak);
  }, [data]);

  const total = useMemo(
    () => data.reduce((sum, item) => sum + (Number(item.value ?? item.count) || 0), 0),
    [data]
  );

  const plotW = chartWidth - PAD.left - PAD.right;
  const plotH = HEIGHT - PAD.top - PAD.bottom;
  const barGap = 12;
  const barCount = Math.max(data.length, 1);
  const slotWidth = plotW / barCount;
  const barWidth = Math.min(96, Math.max(24, slotWidth - barGap));
  const getBarX = (index) =>
    PAD.left + index * slotWidth + (slotWidth - barWidth) / 2;

  const shellClassName = `ptw-dash-shell ptw-dash-bar-chart${
    clickable ? " ptw-dash-shell--clickable" : ""
  }`;

  const shellProps = clickable
    ? {
        role: "button",
        tabIndex: 0,
        onClick,
        onKeyDown: (event) => handleDashboardActivate(event, onClick),
        "aria-label": `${title}. Open related permits.`
      }
    : {};

  return (
    <section className={shellClassName} {...shellProps}>
      <header className="ptw-dash-shell__head">
        <div className="ptw-dash-shell__intro">
          <p className="ptw-dash-shell__eyebrow">Distribution</p>
          <h3 className="ptw-dash-shell__title">{title}</h3>
          {description ? (
            <p className="ptw-dash-shell__desc">
              {clickable ? `${description} Click to view permits.` : description}
            </p>
          ) : null}
        </div>
        <div className="ptw-dash-shell__metric">
          <strong>{total}</strong>
          <span>Total</span>
        </div>
      </header>

      <div className="ptw-dash-shell__body">
        {!data.length || total === 0 ? (
          clickable ? (
            <button
              type="button"
              className="ptw-dash-bar-chart__empty-action"
              onClick={onClick}
            >
              {emptyMessage}
            </button>
          ) : (
            <p className="ptw-dash-bar-chart__empty">{emptyMessage}</p>
          )
        ) : (
          <div ref={canvasRef} className="ptw-dash-bar-chart__canvas-wrap">
            <svg
              className="ptw-dash-bar-chart__svg"
              viewBox={`0 0 ${chartWidth} ${HEIGHT}`}
              preserveAspectRatio="xMidYMid meet"
              role="img"
              aria-label={title}
            >
              {[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
                const y = PAD.top + plotH - ratio * plotH;
                const tick = Math.round(maxValue * ratio);
                return (
                  <g key={ratio}>
                    <line
                      x1={PAD.left}
                      y1={y}
                      x2={chartWidth - PAD.right}
                      y2={y}
                      className="ptw-dash-bar-chart__grid-line"
                    />
                    <text
                      x={PAD.left - 8}
                      y={y}
                      className="ptw-dash-bar-chart__y-label"
                      textAnchor="end"
                      dominantBaseline="middle"
                    >
                      {tick}
                    </text>
                  </g>
                );
              })}

              {data.map((item, index) => {
                const value = Number(item.value ?? item.count) || 0;
                const barH = maxValue > 0 ? (value / maxValue) * plotH : 0;
                const x = getBarX(index);
                const y = PAD.top + plotH - barH;
                const color = item.color || accentColor;
                const label = item.label || item.name || `#${index + 1}`;

                const activateBar = () => {
                  if (onBarClick) {
                    onBarClick(item, index);
                    return;
                  }
                  onClick?.();
                };

                return (
                  <g key={`${label}-${index}`}>
                    <rect
                      x={x}
                      y={y}
                      width={barWidth}
                      height={barH}
                      rx="6"
                      fill={color}
                      opacity="0.9"
                      pointerEvents="none"
                    >
                      <title>{`${label}: ${value}`}</title>
                    </rect>
                    <text
                      x={x + barWidth / 2}
                      y={y - 6}
                      className="ptw-dash-bar-chart__value-label"
                      textAnchor="middle"
                      pointerEvents="none"
                    >
                      {value > 0 ? value : ""}
                    </text>
                    <text
                      x={x + barWidth / 2}
                      y={HEIGHT - 12}
                      className="ptw-dash-bar-chart__x-label"
                      textAnchor="middle"
                      pointerEvents="none"
                    >
                      {formatAxisLabel(label, slotWidth)}
                    </text>
                    {clickable ? (
                      <rect
                        x={x}
                        y={PAD.top}
                        width={barWidth}
                        height={plotH}
                        fill="transparent"
                        className="ptw-dash-chart__bar-hit"
                        tabIndex={0}
                        role="button"
                        aria-label={`${label}: ${value}. Open related permits.`}
                        onClick={(event) => {
                          event.stopPropagation();
                          activateBar();
                        }}
                        onKeyDown={(event) => {
                          if (event.key === "Enter" || event.key === " ") {
                            event.preventDefault();
                            event.stopPropagation();
                            activateBar();
                          }
                        }}
                      />
                    ) : null}
                  </g>
                );
              })}
            </svg>
          </div>
        )}
      </div>
    </section>
  );
}
