"use client";
import type { FinancialRow, FinancialsResponse } from "@/types/api";
import { fmtLarge } from "@/lib/format";
import { CurrencyWarning } from "./CurrencyWarning";

type StatementKey = "income" | "balance" | "cash_flow";
type PeriodKey = "annual" | "quarterly";

type Props = {
  data: FinancialsResponse;
  statement: StatementKey;
  period: PeriodKey;
  onChangePeriod: (p: PeriodKey) => void;
};

function fmtFinVal(val: number | null | undefined, isMargin: boolean, currency: string): string {
  if (val === null || val === undefined) return "—";
  if (isMargin) return `${(val * 100).toFixed(1)}%`;
  return fmtLarge(val, currency);
}

function FinRow({ row, lastColIdx, currency }: { row: FinancialRow; lastColIdx: number; currency: string }) {
  if (row.is_section) {
    return (
      <tr className="psm-fin-section-row">
        <td className="psm-fin-section-label" colSpan={lastColIdx + 2}>
          {row.label}
        </td>
      </tr>
    );
  }

  const cls = [
    "psm-fin-row",
    row.is_total ? "is-total" : "",
    row.is_margin ? "is-margin" : "",
    row.indent === 1 ? "is-indent" : "",
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <tr className={cls}>
      <td className="psm-fin-label">{row.label}</td>
      {row.values.map((val, i) => (
        <td
          key={i}
          className={[
            "psm-fin-val",
            i === lastColIdx ? "accent" : "",
            val !== null && val < 0 && !row.is_margin ? "neg" : "",
          ]
            .filter(Boolean)
            .join(" ")}
        >
          {fmtFinVal(val, row.is_margin, currency)}
        </td>
      ))}
    </tr>
  );
}

export function FinancialsCard({
  data,
  statement,
  period,
  onChangePeriod,
}: Props) {
  const stmt = data[statement];
  const lastColIdx = stmt.columns.length - 1;

  return (
    <section className="psm-card psm-financials-card">
      <div className="psm-fin-header">
        <div className="psm-fin-period">
          {(["annual", "quarterly"] as PeriodKey[]).map((p) => (
            <button
              key={p}
              type="button"
              className={`psm-fin-period-btn${period === p ? " active" : ""}`}
              onClick={() => onChangePeriod(p)}
            >
              {p === "annual" ? "ANNUAL" : "QUARTERLY"}
            </button>
          ))}
        </div>
      </div>

      {stmt.columns.length === 0 ? (
        <p className="psm-muted-copy psm-fin-empty">Statement data unavailable.</p>
      ) : (
        <div className="psm-fin-table-wrap">
          <table className="psm-fin-table">
            <thead>
              <tr>
                <th className="psm-fin-label-col">
                  {data.currency} (millions)
                  <CurrencyWarning warning={data.currency_warning} />
                </th>
                {stmt.columns.map((col, i) => (
                  <th
                    key={i}
                    className={`psm-fin-val-col${i === lastColIdx ? " accent" : ""}`}
                  >
                    {col}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {stmt.rows.map((row, i) => (
                <FinRow key={i} row={row} lastColIdx={lastColIdx} currency={data.currency} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
