<script lang="ts">
  import type { OpportunityForecast } from "../types";
  import { formatCurrency, formatDate } from "../types";
  import NoResultsMonkey from "../../../../../components/NoResultsMonkey.svelte";

  export let forecasts: OpportunityForecast[];
</script>

<div class="forecasts-tab">
  {#if forecasts.length === 0}
    <div class="tab-empty">
      <NoResultsMonkey message="No forecast data available" />
    </div>
  {:else}
    <div class="forecasts-table-wrap">
      <table class="forecasts-table">
        <thead>
          <tr>
            <th>Type</th>
            <th>Month</th>
            <th class="num">Revenue</th>
            <th class="num">Cost</th>
            <th class="num">Margin</th>
            <th class="num">Probability</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          {#each forecasts as f (f.id)}
            <tr>
              <td>{f.forecastType ?? "—"}</td>
              <td>{formatDate(f.forecastMonth)}</td>
              <td class="num">{formatCurrency(f.revenue)}</td>
              <td class="num">{formatCurrency(f.cost)}</td>
              <td class="num">
                {f.revenue != null && f.cost != null
                  ? formatCurrency(f.revenue - f.cost)
                  : "—"}
              </td>
              <td class="num">
                {f.forecastPercentage != null
                  ? `${f.forecastPercentage}%`
                  : "—"}
              </td>
              <td>
                <span
                  class="forecast-status-badge"
                  class:included={f.includedFlag}
                >
                  {f.status?.name ?? "—"}
                </span>
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    </div>

    <!-- Revenue summary -->
    <div class="forecasts-summary">
      <div class="forecast-summary-item">
        <span class="forecast-summary-label">Total Revenue</span>
        <span class="forecast-summary-value">
          {formatCurrency(
            forecasts.reduce((sum, f) => sum + (f.revenue ?? 0), 0),
          )}
        </span>
      </div>
      <div class="forecast-summary-item">
        <span class="forecast-summary-label">Total Cost</span>
        <span class="forecast-summary-value">
          {formatCurrency(forecasts.reduce((sum, f) => sum + (f.cost ?? 0), 0))}
        </span>
      </div>
      <div class="forecast-summary-item">
        <span class="forecast-summary-label">Total Margin</span>
        <span class="forecast-summary-value">
          {formatCurrency(
            forecasts.reduce(
              (sum, f) => sum + ((f.revenue ?? 0) - (f.cost ?? 0)),
              0,
            ),
          )}
        </span>
      </div>
    </div>
  {/if}
</div>
