// One year's row in the journal validation report table — Task 10, wizard
// Step 4. Green when clean (errors === 0), loud red when not, with an
// expandable list of error groups (message x count) and the void-line
// notices journal-load.ts's YearResult carries (voidCount/fullyVoidEntryCount
// — see tools/lib/journal-load.ts and server/src/imports.ts's yearReport()).

import { useState } from "react";

export interface ErrorGroup {
  error: string;
  count: number;
}

export interface YearReportData {
  year: number;
  batchId: number;
  status: string;
  isNew: boolean;
  entries: number;
  rows: number;
  errors: number;
  errorGroups: ErrorGroup[];
  voidCount: number;
  fullyVoidEntryCount: number;
}

export function YearReportRow({ year }: { year: YearReportData }) {
  const [expanded, setExpanded] = useState(false);
  const clean = year.errors === 0;
  const hasVoidNotices = year.voidCount > 0 || year.fullyVoidEntryCount > 0;

  return (
    <div className={`year-row${clean ? " year-row-clean" : " year-row-dirty"}`}>
      <div className="year-row-main">
        <div className="year-row-label">
          <span className="year-row-year">{year.year}</span>
          <span className="year-row-stat">
            {year.entries} {year.entries === 1 ? "entry" : "entries"} &middot; {year.rows} rows
          </span>
        </div>
        <div className="year-row-status">
          {clean ? (
            <span className="chip">Ready to post</span>
          ) : (
            <span className="chip chip-bad">
              {year.errors} {year.errors === 1 ? "error" : "errors"}
            </span>
          )}
        </div>
      </div>

      {hasVoidNotices && (
        <div className="year-row-void">
          {year.voidCount > 0 &&
            `${year.voidCount} zero-amount ${year.voidCount === 1 ? "line" : "lines"} will be skipped (voided transactions or capped payroll tax).`}
          {year.voidCount > 0 && year.fullyVoidEntryCount > 0 && " "}
          {year.fullyVoidEntryCount > 0 &&
            `${year.fullyVoidEntryCount} ${year.fullyVoidEntryCount === 1 ? "entry is" : "entries are"} entirely void — no journal entry will be created for ${year.fullyVoidEntryCount === 1 ? "it" : "them"}.`}
        </div>
      )}

      {!clean && (
        <div className="year-row-errors">
          <button type="button" className="year-row-toggle" onClick={() => setExpanded((v) => !v)}>
            {expanded ? "Hide details" : "Show details"}
          </button>
          {expanded && (
            <ul className="error-groups">
              {year.errorGroups.map((g, i) => (
                <li key={i}>
                  <span>{g.error}</span>
                  <span className="error-groups-count">
                    &times;{g.count}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
}
