import type { ReactNode } from "react";
import { useI18n } from "../../i18n/I18nContext";
import type { UsageEvent } from "../../lib/usageMeter";
import {
  usageEventCostText,
  usageEventSubtitle,
  usageEventTitle,
} from "../../lib/usageEventI18n";
import { formatLocalDateTime } from "../../lib/time";
import { Pager } from "../ui/Pager";

type Props = {
  events: UsageEvent[];
  page: number;
  pageSize: number;
  onPageChange: (p: number) => void;
  pageSlice: <T>(list: T[], page: number, size: number) => T[];
  emptyAction?: ReactNode;
};

export function UsageLedger({
  events,
  page,
  pageSize,
  onPageChange,
  pageSlice,
  emptyAction,
}: Props) {
  const { t } = useI18n();

  if (events.length === 0) {
    return <div className="hb-usage-ledger-empty">{emptyAction}</div>;
  }

  return (
    <div className="hb-stack">
      <ul className="hb-usage-ledger">
        {pageSlice(events, page, pageSize).map((e) => {
          const title = usageEventTitle(e, t);
          const sub = usageEventSubtitle(e, t);
          const cost = usageEventCostText(e, t);
          return (
            <li
              key={e.id}
              className="hb-usage-ledger__row"
              title={`${title} · ${sub}`}
            >
              <div className="hb-usage-ledger__main">
                <strong>{title}</strong>
                <span className="text-muted hb-usage-ledger__when">
                  {sub}
                  {" · "}
                  {formatLocalDateTime(e.created_at)}
                </span>
              </div>
              <span
                className="hb-usage-ledger__cost"
                aria-label={
                  e.key_mode === "byok" || e.credits === 0
                    ? t("usage.event.cost.byokAria")
                    : t("usage.ledger.costAria", { n: e.credits })
                }
              >
                {cost}
              </span>
            </li>
          );
        })}
      </ul>
      <Pager total={events.length} page={page} pageSize={pageSize} onPageChange={onPageChange} />
    </div>
  );
}
