import React, { useMemo, useState } from "react";

function chartScaleMax(maxMinutes) {
  const n = Number(maxMinutes) || 0;
  if (n <= 0) return 10;
  const mag = 10 ** Math.floor(Math.log10(n));
  const norm = n / mag;
  const ceilNorm = norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 5 ? 5 : 10;
  return ceilNorm * mag;
}

/**
 * @param {{ downtimeTrend: Array<{ month: string, minutes: number }> }} props
 */
const DowntimeTrend = ({ downtimeTrend = [] }) => {
  const [year, setYear] = useState("2026");
  const [period, setPeriod] = useState("monthly");

  const maxRaw = useMemo(
    () => Math.max(0, ...downtimeTrend.map((d) => Number(d.minutes) || 0)),
    [downtimeTrend]
  );

  const yMax = useMemo(() => chartScaleMax(maxRaw), [maxRaw]);

  const yTicks = useMemo(() => {
    const steps = 4;
    const ticks = [];
    for (let i = steps; i >= 0; i--) {
      ticks.push(Math.round((yMax * i) / steps));
    }
    return ticks;
  }, [yMax]);

  const headerTools = (
    <div className="portal-panel__toolbar portal-panel__toolbar--align-end">
      <label className="portal-mini-field portal-mini-field--row">
        <span className="portal-mini-field__static">Year</span>
        <select className="portal-select" value={year} onChange={(e) => setYear(e.target.value)}>
          <option value="2026">2026</option>
          <option value="2025">2025</option>
          <option value="2024">2024</option>
        </select>
      </label>
      <label className="portal-mini-field portal-mini-field--row">
        <span className="portal-mini-field__static">Period</span>
        <select className="portal-select" value={period} onChange={(e) => setPeriod(e.target.value)}>
          <option value="daily">Daily</option>
          <option value="monthly">Monthly</option>
          <option value="quarterly">Quarterly</option>
        </select>
      </label>
    </div>
  );

  if (!downtimeTrend.length) {
    return (
      <div className="swi-panel portal-chart-panel">
        <div className="portal-panel__head">
          <div>
            <h3 className="swi-panel__title portal-panel__title">Downtime trends</h3>
            <p className="portal-panel__desc">Procedure-related minutes by period (illustrative).</p>
          </div>
          {headerTools}
        </div>
        <p className="swi-muted">No downtime events recorded for this range.</p>
      </div>
    );
  }

  return (
    <div className="swi-panel portal-chart-panel">
      <div className="portal-panel__head">
        <div>
          <h3 className="swi-panel__title portal-panel__title">Downtime trends</h3>
          <p className="portal-panel__desc">Procedure-related minutes by month (illustrative).</p>
        </div>
        {headerTools}
      </div>

      <div className="swi-chart-pro" aria-label="Downtime bar chart">
        <div className="swi-chart-pro__y-axis">
          {yTicks.map((v, i) => (
            <span key={i} className="swi-chart-pro__y-tick">
              {v}
            </span>
          ))}
        </div>
        <div className="swi-chart-pro__plot">
          <div className="swi-chart-pro__grid" aria-hidden>
            {[1, 2, 3, 4].map((i) => (
              <div
                key={i}
                className="swi-chart-pro__grid-line"
                style={{ bottom: `${(i / 4) * 100}%` }}
              />
            ))}
          </div>
          <div className="swi-chart-pro__bars">
            {downtimeTrend.map((row) => {
              const minutes = Number(row.minutes) || 0;
              const h = yMax <= 0 ? 0 : Math.min(100, (minutes / yMax) * 100);
              return (
                <div key={row.month} className="swi-chart-pro__col">
                  <div
                    className="swi-chart-pro__bar"
                    style={{ height: `${h}%` }}
                    title={`${row.month}: ${minutes} minutes`}
                  />
                  <span className="swi-chart-pro__x-label">{row.month.slice(5)}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      <p className="swi-chart-pro__unit">Vertical axis: minutes</p>
    </div>
  );
};

export default DowntimeTrend;
