<script lang="ts">
  import { clientFetch } from "$lib/client-fetch";
  import type { WorkflowStatusResponse } from "../types";
  import {
    WORKFLOW_STATUS_LABELS,
    STATUS_ID_TO_KEY,
  } from "$lib/optima-api/modules/sales";
  import type {
    SalesOpportunity,
    WorkflowHistoryEntry,
    OpportunityActivity,
  } from "$lib/optima-api/modules/sales";
  import { formatDateTime } from "../types";

  export let opportunity: SalesOpportunity | null;
  export let workflowStatus: WorkflowStatusResponse | null;
  export let opportunityId: string;

  let historyEntries: WorkflowHistoryEntry[] = [];
  let isLoading = true;
  let loadError: string | null = null;

  // Fetch workflow history on mount
  import { onMount } from "svelte";

  onMount(async () => {
    await fetchHistory();
  });

  async function fetchHistory() {
    isLoading = true;
    loadError = null;
    try {
      const json = await clientFetch<{
        data: { activities: WorkflowHistoryEntry[] };
      }>(`/sales/opportunity/${opportunityId}/workflow/history`);
      historyEntries = json.data?.activities ?? [];
    } catch (err) {
      loadError = err instanceof Error ? err.message : "Failed to load history";
    } finally {
      isLoading = false;
    }
  }

  // Derive stats from history
  $: totalActions = historyEntries.length;

  $: uniqueTypes = (() => {
    const types = new Set<string>();
    for (const e of historyEntries) {
      if (e.optimaType) types.add(e.optimaType);
    }
    return types;
  })();

  $: currentStatusLabel = (() => {
    if (!workflowStatus) return opportunity?.status?.name ?? "Unknown";
    const key = STATUS_ID_TO_KEY[workflowStatus.currentStatusId];
    return key ? WORKFLOW_STATUS_LABELS[key] : workflowStatus.currentStatus;
  })();

  $: isCold = workflowStatus?.coldCheck?.isCold ?? false;
  $: staleDays = workflowStatus?.coldCheck?.daysSinceActivity ?? null;
</script>

<div class="opp-report-tab">
  <div class="opp-report-header">
    <h3 class="overview-section-title">
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        width="16"
        height="16"
      >
        <path
          d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
        />
      </svg>
      Opportunity Report
    </h3>
  </div>

  <!-- Summary Cards -->
  <div class="opp-report-cards">
    <div class="opp-report-card">
      <span class="opp-report-card-label">Current Status</span>
      <span class="opp-report-card-value">{currentStatusLabel}</span>
    </div>
    <div class="opp-report-card">
      <span class="opp-report-card-label">Workflow Actions</span>
      <span class="opp-report-card-value">{totalActions}</span>
    </div>
    <div class="opp-report-card">
      <span class="opp-report-card-label">Activity Types</span>
      <span class="opp-report-card-value">{uniqueTypes.size}</span>
    </div>
    {#if staleDays !== null}
      <div class="opp-report-card" class:opp-report-card-warning={isCold}>
        <span class="opp-report-card-label">Days Since Activity</span>
        <span class="opp-report-card-value">{staleDays}</span>
      </div>
    {/if}
  </div>

  <!-- History Table -->
  <div class="opp-report-section">
    <h4 class="opp-report-section-title">Workflow History</h4>
    {#if isLoading}
      <div class="opp-report-loading">
        <span class="wf-spinner"></span>
        Loading history...
      </div>
    {:else if loadError}
      <div class="opp-report-error">{loadError}</div>
    {:else if historyEntries.length === 0}
      <p class="opp-report-empty">No workflow history for this opportunity.</p>
    {:else}
      <div class="opp-report-table-wrap">
        <table class="opp-report-table">
          <thead>
            <tr>
              <th>Type</th>
              <th>Activity</th>
              <th>Assigned To</th>
              <th>Started</th>
              <th>Closed</th>
            </tr>
          </thead>
          <tbody>
            {#each historyEntries as entry, i (entry.activity.cwActivityId ?? i)}
              {@const act = entry.activity}
              <tr>
                <td>
                  {#if entry.optimaType}
                    <span class="opp-report-type-badge">{entry.optimaType}</span
                    >
                  {:else}
                    <span class="opp-report-type-muted">—</span>
                  {/if}
                </td>
                <td>
                  {#if act.name}
                    <span class="opp-report-activity-name">{act.name}</span>
                  {/if}
                  {#if act.notes}
                    <span class="opp-report-activity-notes">{act.notes}</span>
                  {/if}
                </td>
                <td>{act.assignTo?.name ?? act.cwEnteredBy ?? "System"}</td>
                <td>{formatDateTime(act.cwDateEntered ?? act.dateStart)}</td>
                <td>
                  {#if act.dateEnd}
                    {formatDateTime(act.dateEnd)}
                  {:else}
                    <span class="opp-report-open-badge">Open</span>
                  {/if}
                </td>
              </tr>
            {/each}
          </tbody>
        </table>
      </div>
    {/if}
  </div>
</div>

<style>
  .opp-report-tab {
    padding: 0;
  }

  .opp-report-header {
    margin-bottom: 16px;
  }

  .opp-report-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
  }

  .opp-report-card {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 14px;
    border-radius: 8px;
    background: var(--bg-inset);
    border: 1px solid var(--card-border);
  }

  .opp-report-card.opp-report-card-warning {
    border-color: rgba(245, 158, 11, 0.3);
    background: rgba(245, 158, 11, 0.04);
  }

  .opp-report-card-label {
    font-size: 11px;
    font-weight: 500;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.3px;
  }

  .opp-report-card-value {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
  }

  .opp-report-section {
    margin-bottom: 20px;
  }

  .opp-report-section-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 12px;
  }

  .opp-report-loading {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 20px 0;
    color: var(--text-muted);
    font-size: 13px;
  }

  .opp-report-error {
    padding: 10px;
    border-radius: 6px;
    background: rgba(220, 38, 38, 0.06);
    border: 1px solid rgba(220, 38, 38, 0.15);
    color: #dc2626;
    font-size: 12px;
  }

  .opp-report-empty {
    color: var(--text-muted);
    font-size: 13px;
    font-style: italic;
    margin: 0;
  }

  .opp-report-table-wrap {
    overflow-x: auto;
    border-radius: 8px;
    border: 1px solid var(--card-border);
  }

  .opp-report-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
  }

  .opp-report-table th {
    text-align: left;
    padding: 8px 12px;
    font-weight: 600;
    color: var(--text-secondary);
    background: var(--bg-inset);
    border-bottom: 1px solid var(--card-border);
    white-space: nowrap;
  }

  .opp-report-table td {
    padding: 8px 12px;
    vertical-align: top;
    border-bottom: 1px solid var(--card-border);
    color: var(--text-primary);
  }

  .opp-report-table tr:last-child td {
    border-bottom: none;
  }

  .opp-report-type-badge {
    display: inline-flex;
    padding: 1px 6px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    background: rgba(59, 130, 246, 0.08);
    color: #2563eb;
  }

  .opp-report-type-muted {
    color: var(--text-muted);
  }

  .opp-report-activity-name {
    display: block;
    font-weight: 500;
  }

  .opp-report-activity-notes {
    display: block;
    font-size: 11px;
    color: var(--text-secondary);
    margin-top: 2px;
    line-height: 1.4;
    max-width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .opp-report-open-badge {
    display: inline-flex;
    padding: 1px 6px;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    background: rgba(34, 197, 94, 0.1);
    color: #16a34a;
  }

  @media (max-width: 768px) {
    .opp-report-cards {
      grid-template-columns: 1fr 1fr;
    }
  }
</style>
