// Profit & loss tab — Task 9. GET /api/c/reports/pnl?from=&to= (server/src/
// reports.ts) is already presentation-signed (income/expense flipped so
// "more of this" reads as a bigger positive number, CLAUDE.md §9) — this
// component never re-derives a sign, it just formats and displays. Period
// picker is date inputs plus three quick presets, per the Task 9 brief
// ("simpler: from/to date inputs with quick presets").

import { useMemo, useState } from "react";
import { useCompany } from "../lib/company";
import { useApiGet } from "../lib/useApiGet";
import { fmtMoney } from "../lib/money";
import { yearRange } from "../lib/date";
import { ErrorBanner } from "../components/ErrorBanner";
import { AccountLink } from "./AccountLink";
import type { NavTarget } from "../lib/useHashView";

interface PnlLine {
  accountId: string;
  code: string;
  name: string;
  amount: string;
}

interface PnlData {
  from: string | null;
  to: string | null;
  income: PnlLine[];
  incomeTotal: string;
  expense: PnlLine[];
  expenseTotal: string;
  net: string;
}

type Preset = "this-year" | "last-year" | "all-time" | "custom";

function buildPath(from: string, to: string): string {
  const params = new URLSearchParams();
  if (from) params.set("from", from);
  if (to) params.set("to", to);
  const qs = params.toString();
  return `/api/c/reports/pnl${qs ? `?${qs}` : ""}`;
}

export function ProfitLossReport({
  onSelectAccount,
  navigate,
}: {
  onSelectAccount: (accountId: string) => void;
  navigate: (target: NavTarget) => void;
}) {
  const { selectedCompanyId } = useCompany();
  const currentYear = new Date().getFullYear(); // a calendar year label, not money — fine as a JS number
  const defaultRange = useMemo(() => yearRange(currentYear), [currentYear]);

  const [from, setFrom] = useState(defaultRange.from);
  const [to, setTo] = useState(defaultRange.to);
  const [preset, setPreset] = useState<Preset>("this-year");

  const path = buildPath(from, to);
  const { data, loading, error, retry } = useApiGet<PnlData>(path, selectedCompanyId);

  function applyPreset(next: Preset) {
    setPreset(next);
    if (next === "this-year") {
      const r = yearRange(currentYear);
      setFrom(r.from);
      setTo(r.to);
    } else if (next === "last-year") {
      const r = yearRange(currentYear - 1);
      setFrom(r.from);
      setTo(r.to);
    } else if (next === "all-time") {
      setFrom("");
      setTo("");
    }
  }

  const hasRows = (data?.income.length ?? 0) > 0 || (data?.expense.length ?? 0) > 0;

  return (
    <div>
      <div className="report-toolbar">
        <div className="presets">
          <button type="button" aria-pressed={preset === "this-year"} onClick={() => applyPreset("this-year")}>
            This year
          </button>
          <button type="button" aria-pressed={preset === "last-year"} onClick={() => applyPreset("last-year")}>
            Last year
          </button>
          <button type="button" aria-pressed={preset === "all-time"} onClick={() => applyPreset("all-time")}>
            All time
          </button>
        </div>
        <div className="date-inputs">
          <label>
            From
            <input
              type="date"
              value={from}
              onChange={(ev) => {
                setFrom(ev.target.value);
                setPreset("custom");
              }}
            />
          </label>
          <label>
            To
            <input
              type="date"
              value={to}
              onChange={(ev) => {
                setTo(ev.target.value);
                setPreset("custom");
              }}
            />
          </label>
        </div>
        <button
          type="button"
          className="btn print-btn"
          onClick={() => navigate({ view: "print", printType: "pnl", params: { from, to } })}
        >
          Print / Save as PDF
        </button>
      </div>

      {error && <ErrorBanner message={error} onRetry={retry} />}
      {loading && !data && <p className="msg-inline">Loading&hellip;</p>}
      {!loading && !error && data && !hasRows && (
        <div className="empty-state">No income or spending in this period.</div>
      )}

      {data && hasRows && (
        <div className="card">
          <table>
            <thead>
              <tr>
                <th>Account</th>
                <th className="num">Amount</th>
              </tr>
            </thead>
            <tbody>
              <tr className="section-row">
                <td colSpan={2}>Income</td>
              </tr>
              {data.income.map((row) => (
                <tr key={row.accountId}>
                  <td>
                    <AccountLink id={row.accountId} name={row.name} onSelect={onSelectAccount} />
                  </td>
                  <td className="num">{fmtMoney(row.amount)}</td>
                </tr>
              ))}
              <tr className="total-row">
                <td>Total income</td>
                <td className="num">{fmtMoney(data.incomeTotal)}</td>
              </tr>

              <tr className="section-row">
                <td colSpan={2}>Expenses</td>
              </tr>
              {data.expense.map((row) => (
                <tr key={row.accountId}>
                  <td>
                    <AccountLink id={row.accountId} name={row.name} onSelect={onSelectAccount} />
                  </td>
                  <td className="num">{fmtMoney(row.amount)}</td>
                </tr>
              ))}
              <tr className="total-row">
                <td>Total expenses</td>
                <td className="num">{fmtMoney(data.expenseTotal)}</td>
              </tr>

              <tr className="net-row">
                <td>Kept</td>
                <td className="num">{fmtMoney(data.net)}</td>
              </tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
