<script lang="ts">
  import { onMount } from "svelte";
  import { clientFetch } from "$lib/client-fetch";
  import type {
    WorkflowHistoryEntry,
    WorkflowTimeEntry,
    OpportunityActivity,
  } from "$lib/optima-api/modules/sales";
  import { formatDateTime } from "../types";
  import NoResultsMonkey from "../../../../../components/NoResultsMonkey.svelte";

  export let opportunityId: string;
  export let activities: OpportunityActivity[] = [];

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

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

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

  export function refresh() {
    fetchHistory();
  }

  // ── Derived note items from activities and time entries ──

  type ActivityNoteItem = {
    kind: "activity";
    hist: WorkflowHistoryEntry;
    when: string;
  };

  type TimeEntryNoteItem = {
    kind: "timeEntry";
    te: WorkflowTimeEntry;
    optimaType: string;
    when: string;
  };

  type NoteItem = ActivityNoteItem | TimeEntryNoteItem;

  $: noteItems = (() => {
    let items: WorkflowHistoryEntry[];
    if (workflowHistory.length > 0) {
      items = workflowHistory;
    } else {
      items = (activities ?? []).map((a) => ({
        activity: a,
        optimaType: "",
        quoteId: null,
        parentActivityId: null,
        closed: null as unknown as boolean,
        closedAt: null,
        timeEntries: [],
      }));
    }

    const result: NoteItem[] = [];

    for (const hist of items) {
      if (hist.activity.notes?.trim()) {
        const when = hist.activity.cwDateEntered ?? hist.activity.dateStart ?? "";
        result.push({ kind: "activity", hist, when });
      }
      for (const te of hist.timeEntries ?? []) {
        if (te.notes?.trim()) {
          const when = te.timeStart ?? te.dateStart ?? "";
          result.push({ kind: "timeEntry", te, optimaType: hist.optimaType, when });
        }
      }
    }

    return result.sort((a, b) => b.when.localeCompare(a.when));
  })();

  function initials(name: string | null | undefined): string {
    if (!name) return "?";
    return name
      .split(" ")
      .map((p) => p[0])
      .join("")
      .slice(0, 2)
      .toUpperCase();
  }
</script>

<div class="notes-tab">
  <div class="notes-header">
    <div class="notes-header-left">
      {#if !isLoading}
        <span class="notes-count">
          {noteItems.length} note{noteItems.length === 1 ? "" : "s"}
        </span>
      {/if}
    </div>
    <button
      class="notes-add-btn"
      on:click={fetchHistory}
      disabled={isLoading}
      title="Refresh"
      type="button"
    >
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        width="13"
        height="13"
        class:at-spinning={isLoading}
      >
        <polyline points="23 4 23 10 17 10" />
        <polyline points="1 20 1 14 7 14" />
        <path
          d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"
        />
      </svg>
      Refresh
    </button>
  </div>

  {#if isLoading}
    <div class="at-loading">
      <span class="wf-spinner"></span>
      <span>Loading notes…</span>
    </div>
  {:else if loadError}
    <div class="at-error">{loadError}</div>
  {:else if noteItems.length === 0}
    <div class="tab-empty">
      <NoResultsMonkey message="No notes on activities or time entries" />
    </div>
  {:else}
    <div class="notes-list">
      {#each noteItems as item}
        {#if item.kind === "activity"}
          {@const act = item.hist.activity}
          <div class="note-card">
            <div class="note-card-header">
              <div class="note-header-left">
                <div
                  class="note-avatar"
                  title={act.assignTo?.name ?? act.cwEnteredBy ?? "System"}
                >
                  {initials(act.assignTo?.name ?? act.cwEnteredBy)}
                </div>
                <div class="note-author-info">
                  <span class="note-author-name">
                    {act.assignTo?.name ?? act.cwEnteredBy ?? "System"}
                  </span>
                  <span class="note-timestamp">
                    {formatDateTime(act.cwDateEntered ?? act.dateStart)}
                  </span>
                </div>
              </div>
              <div class="note-header-right">
                <span class="note-source-badge note-source-activity">Activity</span>
                {#if item.hist.optimaType}
                  <span class="note-type-badge">{item.hist.optimaType}</span>
                {/if}
              </div>
            </div>
            <div class="note-card-body">
              <p class="note-text">{act.notes ?? ""}</p>
            </div>
          </div>
        {:else}
          {@const te = item.te}
          <div class="note-card note-card-time-entry">
            <div class="note-card-header">
              <div class="note-header-left">
                <div class="note-avatar" title={te.member?.name ?? te.memberId ?? "Unknown"}>
                  {initials(te.member?.name ?? te.memberId)}
                </div>
                <div class="note-author-info">
                  <span class="note-author-name">{te.member?.name ?? te.memberId ?? "Unknown"}</span>
                  <span class="note-timestamp">
                    {formatDateTime(te.timeStart ?? te.dateStart)}
                  </span>
                </div>
              </div>
              <div class="note-header-right">
                <span class="note-source-badge note-source-time-entry">Time Entry</span>
                {#if te.billableFlag}
                  <span class="note-type-badge">Billable</span>
                {/if}
                {#if te.actualHours != null}
                  <span class="note-type-badge">{te.actualHours}h</span>
                {/if}
              </div>
            </div>
            <div class="note-card-body">
              <p class="note-text">{te.notes ?? ""}</p>
            </div>
          </div>
        {/if}
      {/each}
    </div>
  {/if}
</div>
