<script>
  import { onMount } from "svelte";
  import { get, post } from "../lib/api.js";

  let dates = $state([]);
  let selectedDate = $state("");
  let summary = $state(null);
  let conversations = $state([]);
  let selectedConversation = $state(null);
  let messages = $state([]);
  let searchQuery = $state("");
  let searchResults = $state([]);
  let stats = $state(null);
  let loading = $state(false);
  let triggering = $state(false);
  let error = $state("");
  let view = $state("summary"); // summary, list, detail, search, stats

  onMount(async () => {
    try {
      dates = await get("/conversations/dates");
      if (dates.length) selectDate(dates[0]);
      loadStats();
    } catch (e) {
      error = e.body?.detail || "Failed to load dates";
    }
  });

  async function selectDate(d) {
    selectedDate = d;
    view = "summary";
    loading = true;
    error = "";
    try {
      summary = await get(`/conversations/summary/${d}`);
      conversations = await get(`/conversations/list?date=${d}`);
    } catch (e) {
      summary = null;
      if (e.status !== 404) error = e.body?.detail || "Failed to load summary";
    } finally {
      loading = false;
    }
  }

  async function selectConversation(sessionId) {
    view = "detail";
    loading = true;
    try {
      selectedConversation = await get(`/conversations/${sessionId}`);
      messages = await get(`/conversations/${sessionId}/messages`);
    } catch (e) {
      error = "Failed to load conversation";
    } finally {
      loading = false;
    }
  }

  async function search() {
    if (!searchQuery || searchQuery.length < 2) return;
    view = "search";
    loading = true;
    try {
      searchResults = await get(`/conversations/search?q=${encodeURIComponent(searchQuery)}`);
    } catch (e) {
      error = "Search failed";
    } finally {
      loading = false;
    }
  }

  async function loadStats() {
    try {
      stats = await get("/conversations/stats");
    } catch (e) {
      console.error("Failed to load stats", e);
    }
  }

  async function trigger() {
    triggering = true;
    try {
      await post("/conversations/trigger");
      setTimeout(() => selectDate(selectedDate), 5000);
    } catch (e) {
      error = "Trigger failed";
    } finally {
      triggering = false;
    }
  }

  function markdownToHtml(md) {
    if (!md) return "";
    return md
      .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
      .replace(/^### (.+)$/gm, '<h3 class="text-lg font-semibold mt-4 mb-2">$1</h3>')
      .replace(/^## (.+)$/gm, '<h2 class="text-xl font-bold mt-5 mb-2">$1</h2>')
      .replace(/^# (.+)$/gm, '<h1 class="text-2xl font-bold mt-6 mb-3">$1</h1>')
      .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
      .replace(/\*(.+?)\*/g, '<em>$1</em>')
      .replace(/^- (.+)$/gm, '<li class="ml-4">$1</li>')
      .replace(/\n{2,}/g, '<br><br>')
      .replace(/\n/g, '<br>');
  }

  function formatTokens(n) {
    return n ? n.toLocaleString() : "0";
  }
</script>

<div>
  <div class="flex items-center justify-between mb-6">
    <h2 class="text-xl font-bold text-surface-800 dark:text-surface-100">Code Sessions</h2>
    <div class="flex gap-2">
      <button onclick={() => view = "stats"} class="px-3 py-1.5 text-sm font-medium rounded-lg bg-surface-100 hover:bg-surface-200 dark:bg-surface-700 dark:hover:bg-surface-600 transition-colors">
        Stats
      </button>
      <button onclick={trigger} disabled={triggering}
        class="px-3 py-1.5 text-sm font-medium rounded-lg bg-primary-600 text-white hover:bg-primary-700 disabled:opacity-50">
        {triggering ? "Generating..." : "Generate Summary"}
      </button>
    </div>
  </div>

  {#if error}
    <div class="mb-4 p-3 rounded-lg bg-red-50 text-red-700 text-sm dark:bg-red-900/20 dark:text-red-400">{error}</div>
  {/if}

  <!-- Search Bar -->
  <div class="mb-4">
    <input
      type="text"
      bind:value={searchQuery}
      onkeydown={(e) => e.key === "Enter" && search()}
      placeholder="Search conversations..."
      class="w-full px-4 py-2 text-sm border border-surface-200 dark:border-surface-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 dark:bg-surface-700 dark:text-white"
    />
  </div>

  <!-- Date Selector -->
  {#if view !== "search" && view !== "stats"}
    <div class="flex gap-2 mb-6 flex-wrap">
      {#each dates as d}
        <button onclick={() => selectDate(d)}
          class="px-3 py-1.5 text-sm rounded-lg transition-colors {selectedDate === d ? 'bg-primary-600 text-white' : 'bg-surface-100 text-surface-600 hover:bg-surface-200 dark:bg-surface-700 dark:text-surface-300 dark:hover:bg-surface-600'}">
          {d}
        </button>
      {/each}
      {#if !dates.length && !error}
        <p class="text-sm text-surface-400">No conversations yet.</p>
      {/if}
    </div>
  {/if}

  {#if loading}
    <div class="flex justify-center py-12"><div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div></div>
  {:else if view === "summary" && summary}
    <!-- Summary View -->
    <div class="mb-4 grid grid-cols-4 gap-3">
      <div class="bg-white dark:bg-surface-800 rounded-lg p-3 border border-surface-200 dark:border-surface-700">
        <div class="text-xs text-surface-400">Conversations</div>
        <div class="text-xl font-bold text-surface-900 dark:text-white">{summary.conversation_count}</div>
      </div>
      <div class="bg-white dark:bg-surface-800 rounded-lg p-3 border border-surface-200 dark:border-surface-700">
        <div class="text-xs text-surface-400">Messages</div>
        <div class="text-xl font-bold text-surface-900 dark:text-white">{summary.total_messages}</div>
      </div>
      <div class="bg-white dark:bg-surface-800 rounded-lg p-3 border border-surface-200 dark:border-surface-700">
        <div class="text-xs text-surface-400">Tokens</div>
        <div class="text-xl font-bold text-surface-900 dark:text-white">{formatTokens(summary.total_tokens)}</div>
      </div>
      <div class="bg-white dark:bg-surface-800 rounded-lg p-3 border border-surface-200 dark:border-surface-700">
        <div class="text-xs text-surface-400">Projects</div>
        <div class="text-sm font-medium text-surface-900 dark:text-white truncate">{summary.projects?.split(',')[0] || 'N/A'}</div>
      </div>
    </div>

    <div class="prose dark:prose-invert max-w-none bg-white dark:bg-surface-800 rounded-xl p-6 shadow-sm border border-surface-200 dark:border-surface-700 mb-4">
      {@html markdownToHtml(summary.content)}
    </div>

    <!-- Conversation List -->
    <div class="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 shadow-sm overflow-hidden">
      <div class="px-4 py-2 text-xs font-semibold uppercase tracking-wider text-surface-400 border-b border-surface-100 dark:border-surface-700">
        Conversations ({conversations.length})
      </div>
      {#each conversations as conv}
        <button
          onclick={() => selectConversation(conv.session_id)}
          class="w-full px-4 py-3 hover:bg-surface-50 dark:hover:bg-surface-700 border-b border-surface-100 dark:border-surface-700 last:border-0 transition-colors text-left">
          <div class="flex items-center justify-between">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-surface-700 dark:text-surface-200 truncate">{conv.slug || 'Untitled'}</div>
              <div class="text-xs text-surface-400 truncate">{conv.project_path?.split('/').pop() || 'unknown'}</div>
            </div>
            <div class="flex items-center gap-3 text-xs text-surface-400">
              <span>{conv.message_count} msgs</span>
              <span>{formatTokens(conv.total_tokens)} tokens</span>
            </div>
          </div>
        </button>
      {/each}
    </div>

  {:else if view === "detail" && selectedConversation}
    <!-- Conversation Detail -->
    <button onclick={() => view = "summary"} class="mb-4 text-sm text-primary-600 hover:text-primary-700">← Back to summary</button>

    <div class="bg-white dark:bg-surface-800 rounded-xl p-4 border border-surface-200 dark:border-surface-700 mb-4">
      <h3 class="text-lg font-bold text-surface-900 dark:text-white mb-2">{selectedConversation.slug || 'Untitled'}</h3>
      <div class="grid grid-cols-2 gap-2 text-sm">
        <div><span class="text-surface-400">Project:</span> <span class="text-surface-700 dark:text-surface-300">{selectedConversation.project_path?.split('/').pop()}</span></div>
        <div><span class="text-surface-400">Branch:</span> <span class="text-surface-700 dark:text-surface-300">{selectedConversation.git_branch || 'N/A'}</span></div>
        <div><span class="text-surface-400">Messages:</span> <span class="text-surface-700 dark:text-surface-300">{selectedConversation.message_count}</span></div>
        <div><span class="text-surface-400">Tokens:</span> <span class="text-surface-700 dark:text-surface-300">{formatTokens(selectedConversation.total_input_tokens + selectedConversation.total_output_tokens)}</span></div>
      </div>
    </div>

    <!-- Messages -->
    <div class="space-y-3">
      {#each messages as msg}
        <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
          <div class="flex items-center justify-between mb-2">
            <span class="text-xs font-semibold uppercase {msg.role === 'user' ? 'text-blue-600' : 'text-green-600'}">{msg.role}</span>
            <span class="text-xs text-surface-400">{msg.timestamp?.slice(11, 19)}</span>
          </div>
          <div class="text-sm text-surface-700 dark:text-surface-300 whitespace-pre-wrap">{msg.content?.slice(0, 500)}{msg.content?.length > 500 ? '...' : ''}</div>
          {#if msg.tool_calls?.length}
            <div class="mt-2 pt-2 border-t border-surface-100 dark:border-surface-700">
              <div class="text-xs font-medium text-surface-400 mb-1">Tools: {msg.tool_calls.map(t => t.name).join(', ')}</div>
            </div>
          {/if}
          {#if msg.input_tokens || msg.output_tokens}
            <div class="mt-2 text-xs text-surface-400">
              {msg.input_tokens ? `${msg.input_tokens} in` : ''} {msg.output_tokens ? `${msg.output_tokens} out` : ''}
            </div>
          {/if}
        </div>
      {/each}
    </div>

  {:else if view === "search"}
    <!-- Search Results -->
    <button onclick={() => view = "summary"} class="mb-4 text-sm text-primary-600 hover:text-primary-700">← Back</button>
    <div class="bg-white dark:bg-surface-800 rounded-xl border border-surface-200 dark:border-surface-700 shadow-sm overflow-hidden">
      <div class="px-4 py-2 text-xs font-semibold uppercase tracking-wider text-surface-400 border-b border-surface-100 dark:border-surface-700">
        Search Results ({searchResults.length})
      </div>
      {#each searchResults as conv}
        <button
          onclick={() => selectConversation(conv.session_id)}
          class="w-full px-4 py-3 hover:bg-surface-50 dark:hover:bg-surface-700 border-b border-surface-100 dark:border-surface-700 last:border-0 transition-colors text-left">
          <div class="flex items-center justify-between">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-surface-700 dark:text-surface-200 truncate">{conv.slug || 'Untitled'}</div>
              <div class="text-xs text-surface-400">{conv.started_at?.slice(0, 10)} • {conv.project_path?.split('/').pop()}</div>
            </div>
            <div class="text-xs text-surface-400">{conv.message_count} msgs</div>
          </div>
        </button>
      {/each}
      {#if searchResults.length === 0}
        <div class="px-4 py-8 text-center text-sm text-surface-400">No results found</div>
      {/if}
    </div>

  {:else if view === "stats" && stats}
    <!-- Statistics -->
    <button onclick={() => view = "summary"} class="mb-4 text-sm text-primary-600 hover:text-primary-700">← Back</button>
    <div class="grid grid-cols-3 gap-4 mb-6">
      <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
        <div class="text-sm text-surface-400">Total Conversations</div>
        <div class="text-2xl font-bold text-surface-900 dark:text-white">{stats.total_conversations}</div>
      </div>
      <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
        <div class="text-sm text-surface-400">Total Messages</div>
        <div class="text-2xl font-bold text-surface-900 dark:text-white">{stats.total_messages}</div>
      </div>
      <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
        <div class="text-sm text-surface-400">Total Tokens</div>
        <div class="text-2xl font-bold text-surface-900 dark:text-white">{formatTokens(stats.total_tokens)}</div>
      </div>
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
        <h3 class="text-sm font-semibold text-surface-700 dark:text-surface-200 mb-3">Top Projects</h3>
        {#each stats.top_projects as proj}
          <div class="flex justify-between text-sm py-1">
            <span class="text-surface-600 dark:text-surface-300 truncate">{proj.path?.split('/').pop()}</span>
            <span class="text-surface-400">{proj.count}</span>
          </div>
        {/each}
      </div>

      <div class="bg-white dark:bg-surface-800 rounded-lg p-4 border border-surface-200 dark:border-surface-700">
        <h3 class="text-sm font-semibold text-surface-700 dark:text-surface-200 mb-3">Top Tools</h3>
        {#each stats.top_tools as tool}
          <div class="flex justify-between text-sm py-1">
            <span class="text-surface-600 dark:text-surface-300">{tool.name}</span>
            <span class="text-surface-400">{tool.count}</span>
          </div>
        {/each}
      </div>
    </div>
  {/if}
</div>
