"use client";

/**
 * 6.1 Прогноз по горизонтам — compact table over future_market.forecasts_by_horizon.
 *
 * Columns: горизонт (мес) · индекс дефицита (color-coded) · месяцы предложения ·
 * прогноз спроса/предложения · ставка (% годовых) · фраза чувствительности к ставке.
 *
 * Deficit semantics (HARD, see frontend rules):
 *   deficit_index > 0  → недонасыщенность (повод строить)  → success/green
 *   deficit_index < 0  → затоварка (предложения > спроса)  → warn/danger
 *   deficit_index ≈ 0  → баланс                            → neutral
 */

import { Badge } from "@/components/ui/Badge";
import type { DemandSupplyForecast } from "@/types/forecast";
import {
  DEFICIT_BALANCE_EPS,
  deficitVariant,
  deficitWord,
  fmtNum,
} from "./forecast-helpers";

interface Props {
  forecasts: DemandSupplyForecast[];
  /** Horizon (мес) to emphasise as the current target — highlights its row. */
  targetHorizon?: number;
}

const TH_STYLE: React.CSSProperties = {
  textAlign: "left",
  padding: "8px 12px",
  fontSize: 11,
  fontWeight: 500,
  letterSpacing: "0.04em",
  textTransform: "uppercase",
  color: "var(--fg-secondary)",
  whiteSpace: "nowrap",
  borderBottom: "1px solid var(--border-card)",
};

const TD_STYLE: React.CSSProperties = {
  padding: "10px 12px",
  fontSize: 13,
  color: "var(--fg-primary)",
  verticalAlign: "top",
  borderBottom: "1px solid var(--border-soft)",
  fontVariantNumeric: "tabular-nums",
};

const NUM_TD: React.CSSProperties = { ...TD_STYLE, textAlign: "right" };

export function ForecastHorizonsBlock({ forecasts, targetHorizon }: Props) {
  if (forecasts.length === 0) {
    return (
      <p style={{ fontSize: 13, color: "var(--fg-tertiary)", margin: 0 }}>
        Прогноз по горизонтам недоступен.
      </p>
    );
  }

  const rows = [...forecasts].sort(
    (a, b) => a.horizon_months - b.horizon_months,
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <div style={{ overflowX: "auto" }}>
        <table
          style={{
            width: "100%",
            borderCollapse: "collapse",
            minWidth: 720,
          }}
        >
          <thead>
            <tr>
              <th style={TH_STYLE}>Горизонт</th>
              <th style={TH_STYLE}>Индекс дефицита</th>
              <th style={{ ...TH_STYLE, textAlign: "right" }}>
                Мес. предложения
              </th>
              <th style={{ ...TH_STYLE, textAlign: "right" }}>Прогноз спроса</th>
              <th style={{ ...TH_STYLE, textAlign: "right" }}>
                Прогноз предложения
              </th>
              <th style={{ ...TH_STYLE, textAlign: "right" }}>Ставка</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((f) => {
              const di = f.deficit_index;
              const balanced = Math.abs(di) < DEFICIT_BALANCE_EPS;
              const isTarget = f.horizon_months === targetHorizon;
              return (
                <tr
                  key={f.horizon_months}
                  style={
                    isTarget ? { background: "var(--accent-soft)" } : undefined
                  }
                >
                  <td
                    style={
                      isTarget
                        ? { ...TD_STYLE, fontWeight: 600, color: "var(--accent)" }
                        : TD_STYLE
                    }
                  >
                    {f.horizon_months} мес.
                    {isTarget && (
                      <span
                        style={{
                          marginLeft: 8,
                          fontSize: 11,
                          fontWeight: 500,
                          letterSpacing: "0.04em",
                          textTransform: "uppercase",
                          color: "var(--accent)",
                        }}
                      >
                        Целевой
                      </span>
                    )}
                  </td>
                  <td style={TD_STYLE}>
                    <Badge variant={deficitVariant(di)} size="sm">
                      {di > 0 ? "+" : ""}
                      {fmtNum(di, 2)}
                    </Badge>
                    <span
                      style={{
                        marginLeft: 8,
                        fontSize: 12,
                        color: "var(--fg-secondary)",
                      }}
                    >
                      {deficitWord(di)}
                    </span>
                  </td>
                  <td style={NUM_TD}>
                    {balanced ? "—" : fmtNum(f.months_of_inventory, 1)}
                  </td>
                  <td style={NUM_TD}>
                    {Math.round(f.projected_demand_units).toLocaleString("ru")}
                  </td>
                  <td style={NUM_TD}>
                    {Math.round(f.projected_supply_units).toLocaleString("ru")}
                  </td>
                  <td style={NUM_TD}>{fmtNum(f.rate_future, 2)}%</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Rate-sensitivity phrase — shared across horizons in current data; show
          the distinct phrases once each to avoid noisy repetition. */}
      <RateSensitivityNotes forecasts={rows} />
    </div>
  );
}

function RateSensitivityNotes({
  forecasts,
}: {
  forecasts: DemandSupplyForecast[];
}) {
  const phrases = Array.from(
    new Set(
      forecasts
        .map((f) => f.rate_sensitivity_phrase?.trim())
        .filter((p): p is string => !!p),
    ),
  );
  if (phrases.length === 0) return null;

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 4,
        fontSize: 12,
        color: "var(--fg-tertiary)",
      }}
    >
      <span
        style={{
          fontSize: 11,
          fontWeight: 500,
          letterSpacing: "0.04em",
          textTransform: "uppercase",
          color: "var(--fg-secondary)",
        }}
      >
        Чувствительность к ключевой ставке
      </span>
      {phrases.map((p, i) => (
        <span key={i}>
          {p.charAt(0).toUpperCase() + p.slice(1)}
          {/\.$/.test(p) ? "" : "."}
        </span>
      ))}
    </div>
  );
}
