import React, { useEffect, useMemo, useRef, useState } from "react";
import AddToPersonalizedButton from "../personalized/AddToPersonalizedButton.jsx";
import {
  ASSIGNMENT_PERIOD_OPTIONS,
  buildUserAssignmentTrend,
  chartScaleMax,
} from "../../../utils/userSwiDashboard.js";

function formatPercent(value, total) {
  if (!total) return "0%";
  return `${Math.round((value / total) * 100)}%`;
}

function handleChartKeyDown(event, onClick) {
  if (!onClick) return;
  if (event.key === "Enter" || event.key === " ") {
    event.preventDefault();
    onClick();
  }
}

/**
 * @param {{
 *   assignments?: object[],
 *   loading?: boolean,
 *   onClick?: () => void,
 *   onBarClick?: (item: { period: string, label: string, count: number }, index: number) => void,
 * }} props
 */
export default function UserAssignmentTrendChart({
  assignments = [],
  loading = false,
  onClick,
  onBarClick,
}) {
  const [period, setPeriod] = useState("monthly");
  const [hoverIndex, setHoverIndex] = useState(null);
  const [selectedIndex, setSelectedIndex] = useState(null);
  const [animateBars, setAnimateBars] = useState(false);
  const chartRef = useRef(null);
  const clickable = Boolean(onClick || onBarClick);

  const data = useMemo(
    () => buildUserAssignmentTrend(assignments, period),
    [assignments, period]
  );

  const maxCount = useMemo(
    () => Math.max(0, ...data.map((row) => Number(row.count) || 0)),
    [data]
  );
  const yMax = useMemo(() => chartScaleMax(maxCount), [maxCount]);

  const totalAssigned = useMemo(
    () => data.reduce((sum, row) => sum + (Number(row.count) || 0), 0),
    [data]
  );

  const stats = useMemo(() => {
    if (!data.length) {
      return { peak: 0, peakLabel: "—", average: 0, latest: 0, latestLabel: "—" };
    }
    let peak = 0;
    let peakLabel = "—";
    for (const row of data) {
      const count = Number(row.count) || 0;
      if (count >= peak) {
        peak = count;
        peakLabel = row.label;
      }
    }
    const latest = Number(data[data.length - 1]?.count) || 0;
    const latestLabel = data[data.length - 1]?.label || "—";
    const average =
      data.length > 0
        ? Math.round((totalAssigned / data.length) * 10) / 10
        : 0;
    return { peak, peakLabel, average, latest, latestLabel };
  }, [data, totalAssigned]);

  const activeIndex =
    selectedIndex != null
      ? selectedIndex
      : hoverIndex != null
        ? hoverIndex
        : null;

  const activePoint =
    activeIndex != null && data[activeIndex] ? data[activeIndex] : null;

  const previousPoint =
    activeIndex != null && activeIndex > 0 ? data[activeIndex - 1] : null;

  const delta = useMemo(() => {
    if (!activePoint || !previousPoint) return null;
    const current = Number(activePoint.count) || 0;
    const prev = Number(previousPoint.count) || 0;
    return current - prev;
  }, [activePoint, previousPoint]);

  useEffect(() => {
    setAnimateBars(false);
    const frame = requestAnimationFrame(() => setAnimateBars(true));
    return () => cancelAnimationFrame(frame);
  }, [period, data.length]);

  const periodLabel =
    ASSIGNMENT_PERIOD_OPTIONS.find((item) => item.id === period)?.label ||
    "Monthly";

  const periodTotals = useMemo(() => {
    const totals = {};
    for (const option of ASSIGNMENT_PERIOD_OPTIONS) {
      totals[option.id] = buildUserAssignmentTrend(assignments, option.id).reduce(
        (sum, row) => sum + (Number(row.count) || 0),
        0
      );
    }
    return totals;
  }, [assignments]);

  const handleBarActivate = (row, index) => {
    if (onBarClick) {
      onBarClick(row, index);
      return;
    }
    if (onClick) {
      onClick();
      return;
    }
    setSelectedIndex((prev) => (prev === index ? null : index));
  };

  if (loading) {
    return (
      <section className="swi-assign-trend swi-panel">
        <p className="swi-muted">Loading assignment trend…</p>
      </section>
    );
  }

  const descText = clickable
    ? `Interactive ${periodLabel.toLowerCase()} view — hover or click a bar to open your assignments.`
    : `Interactive ${periodLabel.toLowerCase()} view — hover or click a bar for details.`;

  return (
    // <section className="swi-assign-trend swi-assign-trend--wide swi-panel" aria-label="Assignment trend">
    //   <header className="swi-assign-trend__head">
    //     <div>
    //       <h2 className="swi-assign-trend__title">SWIs assigned to you</h2>
    //       <p className="swi-assign-trend__desc">
    //         Interactive {periodLabel.toLowerCase()} view — hover or click a bar
    //         for details.
    //       </p>
    //     </div>
    //     <div className="swi-assign-trend__head-actions">
    //       <div className="swi-assign-trend__metric" aria-live="polite">
    //       {activePoint ? (
    //         <>
    //           <strong>{activePoint.count}</strong>
    //           <span>{activePoint.label}</span>
    //           {delta != null ? (
    //             <em
    //               className={`swi-assign-trend__delta${
    //                 delta > 0
    //                   ? " swi-assign-trend__delta--up"
    //                   : delta < 0
    //                     ? " swi-assign-trend__delta--down"
    //                     : ""
    //               }`}
    //             >
    //               {delta > 0 ? `+${delta}` : delta} vs previous
    //             </em>
    //           ) : null}
    //         </>
    //       ) : (
    //         <>
    //           <strong>{totalAssigned}</strong>
    //           <span>Total in range</span>
    //         </>
    //       )}
    //       </div>
    //     <AddToPersonalizedButton
    //       widgetId="swiAssignmentTrend"
    //       label="Add"
    //       className="swi-add-to-pd--compact"
    //     />
    //     </div>
    //   </header>

    //   <div
    //     className="swi-assign-trend__periods"
    //     role="tablist"
    //     aria-label="Assignment period"
    //   >
    //     {ASSIGNMENT_PERIOD_OPTIONS.map((option) => (
    //         <button
    //           key={option.id}
    //           type="button"
    //           role="tab"
    //           aria-selected={period === option.id}
    //           className={`swi-assign-trend__period${period === option.id ? " is-active" : ""}`}
    //           onClick={() => {
    //             setPeriod(option.id);
    //             setHoverIndex(null);
    //             setSelectedIndex(null);
    //           }}
    //         >
    //           <span className="swi-assign-trend__period-label">{option.label}</span>
    //           <span className="swi-assign-trend__period-count">
    //             {periodTotals[option.id] ?? 0}
    //           </span>
    //         </button>
    //       ))}
    //   </div>

    //   <div className="swi-assign-trend__insights">
    //     <div className="swi-assign-trend__insight">
    //       <span>Peak</span>
    //       <strong>{stats.peak}</strong>
    //       <small>{stats.peakLabel}</small>
    //     </div>
    //     <div className="swi-assign-trend__insight">
    //       <span>Average</span>
    //       <strong>{stats.average}</strong>
    //       <small>Per {periodLabel.toLowerCase()} bucket</small>
    //     </div>
    //     <div className="swi-assign-trend__insight">
    //       <span>Latest</span>
    //       <strong>{stats.latest}</strong>
    //       <small>{stats.latestLabel}</small>
    //     </div>
    //   </div>

    //   {!data.length ? (
    //     <p className="swi-muted">No assignment history for this period.</p>
    //   ) : (
    //     <div className="swi-assign-trend__chart-wrap">
    //       <div className="swi-assign-trend__y-axis" aria-hidden>
    //         {[1, 0.75, 0.5, 0.25, 0].map((ratio) => (
    //           <span key={ratio}>{Math.round(yMax * ratio)}</span>
    //         ))}
    //       </div>

    //       <div
    //         ref={chartRef}
    //         className="swi-assign-trend__chart"
    //         onMouseLeave={() => setHoverIndex(null)}
    //       >
    //         {data.map((row, index) => {
    //           const count = Number(row.count) || 0;
    //           const heightPct = yMax > 0 ? (count / yMax) * 100 : 0;
    //           const isActive = activeIndex === index;
    //           const isDimmed =
    //             activeIndex != null && activeIndex !== index;

    //           return (
    //             <button
    //               key={row.period}
    //               type="button"
    //               className={`swi-assign-trend__col${isActive ? " is-active" : ""}${isDimmed ? " is-dimmed" : ""}`}
    //               aria-pressed={selectedIndex === index}
    //               aria-label={`${row.label}: ${count} SWI${count === 1 ? "" : "s"} assigned`}
    //               onMouseEnter={() => setHoverIndex(index)}
    //               onFocus={() => setHoverIndex(index)}
    //               onBlur={() => setHoverIndex(null)}
    //               onClick={() =>
    //                 setSelectedIndex((prev) =>
    //                   prev === index ? null : index
    //                 )
    //               }
    //             >
    //               {isActive && activePoint ? (
    //                 <div className="swi-assign-trend__tooltip" role="tooltip">
    //                   <strong>{activePoint.count}</strong>
    //                   <span>{activePoint.label}</span>
    //                   <small>
    //                     {formatPercent(activePoint.count, totalAssigned)} of range
    //                   </small>
    //                 </div>
    //               ) : null}

    //               <div className="swi-assign-trend__bar-track">
    //                 <div
    //                   className={`swi-assign-trend__bar${animateBars ? " is-animated" : ""}`}
    //                   style={{ height: `${heightPct}%` }}
    //                 />
    //                 {isActive ? (
    //                   <span className="swi-assign-trend__bar-glow" aria-hidden />
    //                 ) : null}
    //               </div>

    //               <span className="swi-assign-trend__x-label">{row.label}</span>
    //               <span className="swi-assign-trend__count">{count > 0 ? count : ""}</span>
    //             </button>
    //           );
    //         })}
    //       </div>
    //     </div>
    //   )}

    //   {selectedIndex != null ? (
    //     <p className="swi-assign-trend__hint">
    //       Bar pinned — click again to unpin, or hover another period.
    //     </p>
    //   ) : null}
    // </section>
    <></>
  );
}
