interface FinancialYear {
  year: number;
  cifra_afaceri: number | null;
  profit_net: number | null;
  pierdere_neta: number | null;
  active_imobilizate: number | null;
  active_circulante: number | null;
  datorii: number | null;
  capitaluri_total: number | null;
  numar_salariati: number | null;
}

interface Props {
  data: FinancialYear[];
}

function fmtRon(v: number | null): string {
  if (v == null || !Number.isFinite(v)) return '–';
  if (Math.abs(v) >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(1)} mld`;
  if (Math.abs(v) >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (Math.abs(v) >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return Math.round(v).toString();
}

function fmtNum(v: number | null): string {
  if (v == null) return '–';
  return new Intl.NumberFormat('ro-RO').format(Math.round(Number(v)));
}

export function FinancialTimeline({ data }: Props) {
  if (data.length === 0) {
    return (
      <div className="profile-fin-empty">
        Nu există date financiare publicate la Ministerul Finanțelor pentru acest CUI.
      </div>
    );
  }

  // Sort ASC for timeline
  const ordered = [...data].sort((a, b) => a.year - b.year);

  // Compute scales for bars
  const maxCa = Math.max(...ordered.map((y) => Number(y.cifra_afaceri) || 0));
  const maxProfit = Math.max(
    ...ordered.map((y) => Math.max(Math.abs(Number(y.profit_net) || 0), Math.abs(Number(y.pierdere_neta) || 0))),
  );
  const maxSal = Math.max(...ordered.map((y) => Number(y.numar_salariati) || 0));

  return (
    <div className="profile-fin">
      <div className="profile-fin-grid">
        {/* Cifră de afaceri row */}
        <div className="profile-fin-row">
          <div className="profile-fin-label">
            <div className="profile-fin-metric">Cifră de afaceri netă</div>
            <div className="profile-fin-sub">RON</div>
          </div>
          {ordered.map((y) => {
            const v = Number(y.cifra_afaceri) || 0;
            const pct = maxCa > 0 ? (v / maxCa) * 100 : 0;
            return (
              <div key={y.year} className="profile-fin-cell">
                <div className="profile-fin-bar">
                  <div className="profile-fin-bar-fill profile-fin-bar-ca" style={{ height: `${pct}%` }} />
                </div>
                <div className="profile-fin-value">{fmtRon(v)}</div>
              </div>
            );
          })}
        </div>

        {/* Profit/Pierdere row */}
        <div className="profile-fin-row">
          <div className="profile-fin-label">
            <div className="profile-fin-metric">Profit / Pierdere net</div>
            <div className="profile-fin-sub">RON</div>
          </div>
          {ordered.map((y) => {
            const profit = Number(y.profit_net) || 0;
            const loss = Number(y.pierdere_neta) || 0;
            const v = profit > 0 ? profit : -loss;
            const isLoss = v < 0;
            const pct = maxProfit > 0 ? (Math.abs(v) / maxProfit) * 100 : 0;
            return (
              <div key={y.year} className="profile-fin-cell">
                <div className="profile-fin-bar">
                  <div
                    className={`profile-fin-bar-fill ${isLoss ? 'profile-fin-bar-loss' : 'profile-fin-bar-profit'}`}
                    style={{ height: `${pct}%` }}
                  />
                </div>
                <div className={`profile-fin-value ${isLoss ? 'profile-fin-value-loss' : ''}`}>
                  {v > 0 ? '+' : ''}{fmtRon(v)}
                </div>
              </div>
            );
          })}
        </div>

        {/* Salariați row */}
        <div className="profile-fin-row">
          <div className="profile-fin-label">
            <div className="profile-fin-metric">Număr mediu salariați</div>
            <div className="profile-fin-sub">persoane</div>
          </div>
          {ordered.map((y) => {
            const v = Number(y.numar_salariati) || 0;
            const pct = maxSal > 0 ? (v / maxSal) * 100 : 0;
            return (
              <div key={y.year} className="profile-fin-cell">
                <div className="profile-fin-bar">
                  <div className="profile-fin-bar-fill profile-fin-bar-sal" style={{ height: `${pct}%` }} />
                </div>
                <div className="profile-fin-value">{fmtNum(v)}</div>
              </div>
            );
          })}
        </div>

        {/* Year axis */}
        <div className="profile-fin-row profile-fin-axis">
          <div className="profile-fin-label" />
          {ordered.map((y) => (
            <div key={y.year} className="profile-fin-cell">
              <div className="profile-fin-year">{y.year}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="profile-fin-source">
        Sursă: Ministerul Finanțelor — Situații financiare anuale (data.gov.ro, CC-BY 4.0)
      </div>
    </div>
  );
}
