import { formatDuration } from '../lib/format';

interface Props {
  /** Worked ms per day, index 0 = day 1 of the shown month. */
  values: number[];
  month: string;
}

const HOUR_MS = 3_600_000;

export function BarChart({ values, month }: Props) {
  const maxHours = Math.max(...values) / HOUR_MS;
  const niceMaxHours = Math.max(1, Math.ceil(maxHours));
  const niceMaxMs = niceMaxHours * HOUR_MS;
  const [year, monthIndex] = month.split('-').map(Number);

  const yTicks = [4, 3, 2, 1, 0].map((n) => (niceMaxMs * n) / 4);

  return (
    <div className="bar-chart-wrap">
      <div className="bar-chart-yaxis">
        {yTicks.map((ms) => (
          <span key={ms}>{formatDuration(ms)}</span>
        ))}
      </div>
      <div className="bar-chart-body">
        <div
          className="bar-chart bar-chart-grid"
          role="img"
          aria-label={`Odpracované hodiny podle dne v měsíci ${month}`}
        >
          {values.map((ms, i) => {
            const day = i + 1;
            const heightPct = (ms / niceMaxMs) * 100;
            const label = new Date(year, monthIndex - 1, day).toLocaleDateString('cs-CZ', {
              day: 'numeric',
              month: 'numeric',
            });
            return (
              <div className="bar-col" key={day} title={`${label}: ${formatDuration(ms)}`}>
                <div className="bar" style={{ height: `${heightPct}%` }} />
              </div>
            );
          })}
        </div>
        <div className="bar-chart-labels">
          {values.map((_, i) => {
            const day = i + 1;
            return (
              <div className="bar-col-label" key={day}>
                {day === 1 || day % 5 === 0 ? day : ''}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
