<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { useChatStore } from "@/stores/chat";
import { useSettingsStore } from "@/stores/settings";
import { apiGet } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown";
import ChatMessage from "@/components/ChatMessage.vue";
import type { Note } from "@/types/note";

const props = defineProps<{
  contextNoteId?: number | null;
}>();

const emit = defineEmits<{
  close: [];
}>();

const store = useChatStore();
const settingsStore = useSettingsStore();
const messageInput = ref("");
const messagesEl = ref<HTMLElement | null>(null);
const inputEl = ref<HTMLTextAreaElement | null>(null);

// Note picker state
const attachedNote = ref<{ id: number; title: string } | null>(null);
const showNotePicker = ref(false);
const noteSearchQuery = ref("");
const noteSearchResults = ref<{ id: number; title: string }[]>([]);
const noteSearchLoading = ref(false);
let noteSearchTimer: ReturnType<typeof setTimeout> | null = null;


const streamingRendered = computed(() => {
  if (!store.streamingContent) return "";
  return renderMarkdown(store.streamingContent);
});

watch(
  () => store.streamingContent,
  () => scrollToBottom()
);

function scrollToBottom() {
  nextTick(() => {
    if (messagesEl.value) {
      messagesEl.value.scrollTop = messagesEl.value.scrollHeight;
    }
  });
}

async function sendMessage() {
  const content = messageInput.value.trim();
  if (!content || store.streaming) return;

  // Auto-create conversation if none active
  if (!store.currentConversation) {
    const conv = await store.createConversation();
    await store.fetchConversation(conv.id);
  }

  const contextNoteId = attachedNote.value?.id ?? props.contextNoteId;
  attachedNote.value = null;
  messageInput.value = "";
  resetTextareaHeight();
  scrollToBottom();
  await store.sendMessage(content, contextNoteId);
  scrollToBottom();
}

async function handleSaveAsNote(messageId: number) {
  try {
    await store.saveMessageAsNote(messageId);
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Saved as note");
  } catch {
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Failed to save as note", "error");
  }
}

function autoResize() {
  const el = inputEl.value;
  if (!el) return;
  el.style.height = "auto";
  el.style.height = Math.min(el.scrollHeight, 150) + "px";
}

function resetTextareaHeight() {
  const el = inputEl.value;
  if (!el) return;
  el.style.height = "auto";
}

function onInputKeydown(e: KeyboardEvent) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}

// Note picker
function toggleNotePicker() {
  showNotePicker.value = !showNotePicker.value;
  if (showNotePicker.value) {
    noteSearchQuery.value = "";
    noteSearchResults.value = [];
    nextTick(() => {
      const el = document.querySelector(".panel-note-picker-search") as HTMLInputElement;
      el?.focus();
    });
  }
}

function onNoteSearchInput() {
  if (noteSearchTimer) clearTimeout(noteSearchTimer);
  noteSearchTimer = setTimeout(async () => {
    const q = noteSearchQuery.value.trim();
    if (!q) {
      noteSearchResults.value = [];
      return;
    }
    noteSearchLoading.value = true;
    try {
      const data = await apiGet<{ notes: Note[] }>(
        `/api/notes?q=${encodeURIComponent(q)}&all=true&limit=5`
      );
      noteSearchResults.value = data.notes.map((n) => ({ id: n.id, title: n.title }));
    } catch {
      noteSearchResults.value = [];
    } finally {
      noteSearchLoading.value = false;
    }
  }, 250);
}

function selectNote(note: { id: number; title: string }) {
  attachedNote.value = note;
  showNotePicker.value = false;
}

function removeAttachedNote() {
  attachedNote.value = null;
}

function promoteAutoNote(note: { id: number; title: string }) {
  attachedNote.value = note;
}
</script>

<template>
  <div class="chat-panel-overlay" @click.self="emit('close')">
    <aside class="chat-panel">
      <div class="panel-header">
        <h3>Chat</h3>
        <span v-if="contextNoteId" class="context-indicator">
          Note #{{ contextNoteId }}
        </span>
        <button class="btn-close" @click="emit('close')">&times;</button>
      </div>

      <div ref="messagesEl" class="panel-messages">
        <div class="messages-inner">
          <template v-if="store.currentConversation">
            <ChatMessage
              v-for="msg in store.currentConversation.messages"
              :key="msg.id"
              :message="msg"
              @save-as-note="handleSaveAsNote"
            />
          </template>

          <!-- Context pills -->
          <div
            v-if="store.lastContextMeta?.auto_notes?.length && (store.streaming || store.currentConversation?.messages.length)"
            class="context-pills"
          >
            <span class="context-pills-label">Context:</span>
            <span
              v-for="note in store.lastContextMeta.auto_notes"
              :key="note.id"
              class="context-pill"
            >
              <router-link :to="`/notes/${note.id}`" class="context-pill-link" @click="emit('close')">
                {{ note.title }}
              </router-link>
              <button
                class="context-pill-btn promote"
                @click="promoteAutoNote(note)"
                title="Attach for next message"
              >+</button>
            </span>
          </div>

          <!-- Streaming bubble -->
          <div v-if="store.streaming" class="chat-message role-assistant">
            <div class="streaming-bubble">
              <div class="message-header">
                <span class="role-label">{{ settingsStore.assistantName }}</span>
              </div>
              <details
                v-if="store.streamingThinking"
                class="thinking-block"
                :open="!store.streamingContent"
              >
                <summary class="thinking-summary">Reasoning</summary>
                <pre class="thinking-text">{{ store.streamingThinking }}</pre>
              </details>
              <div class="message-content prose" v-html="streamingRendered"></div>
              <span v-if="!store.streamingThinking" class="typing-indicator"></span>
            </div>
          </div>

          <p
            v-if="!store.currentConversation?.messages.length && !store.streaming"
            class="empty-msg"
          >
            Start chatting...
          </p>
        </div>
      </div>

      <div class="panel-input-wrapper">
        <!-- Attached note pill -->
        <div v-if="attachedNote" class="attached-note">
          <span class="attached-note-pill">
            {{ attachedNote.title }}
            <button class="attached-note-remove" @click="removeAttachedNote">&times;</button>
          </span>
        </div>

        <div class="panel-input">
          <!-- Note picker -->
          <div class="note-picker-wrapper">
            <button
              class="btn-attach"
              @click="toggleNotePicker"
              :disabled="store.streaming || !store.chatReady"
              title="Attach a note"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/>
              </svg>
            </button>
            <div v-if="showNotePicker" class="note-picker-dropdown">
              <input
                class="panel-note-picker-search"
                v-model="noteSearchQuery"
                @input="onNoteSearchInput"
                placeholder="Search notes..."
              />
              <div class="note-picker-results">
                <div
                  v-for="note in noteSearchResults"
                  :key="note.id"
                  class="note-picker-item"
                  @click="selectNote(note)"
                >
                  {{ note.title || "Untitled" }}
                </div>
                <div v-if="noteSearchLoading" class="note-picker-empty">Searching...</div>
                <div v-else-if="noteSearchQuery && !noteSearchResults.length" class="note-picker-empty">
                  No notes found
                </div>
              </div>
            </div>
          </div>

          <textarea
            ref="inputEl"
            v-model="messageInput"
            @keydown="onInputKeydown"
            @input="autoResize"
            :placeholder="store.chatReady ? 'Type a message...' : 'Chat unavailable'"
            :disabled="store.streaming || !store.chatReady"
            rows="1"
          ></textarea>
          <button
            class="btn-send"
            @click="sendMessage"
            :disabled="!messageInput.trim() || store.streaming || !store.chatReady"
          >
            &uarr;
          </button>
        </div>
      </div>
    </aside>
  </div>
</template>

<style scoped>
.chat-panel-overlay {
  position: fixed;
  inset: 0;
  background: var(--color-overlay);
  z-index: 100;
  display: flex;
  justify-content: flex-end;
}

.chat-panel {
  width: 400px;
  max-width: 100vw;
  height: 100%;
  background: var(--color-bg);
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--color-border);
}
.panel-header h3 {
  margin: 0;
  font-size: 1rem;
  flex: 1;
}
.context-indicator {
  font-size: 0.8rem;
  color: var(--color-primary);
  background: var(--color-bg-secondary);
  padding: 0.15rem 0.5rem;
  border-radius: var(--radius-sm);
}
.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--color-text-muted);
  line-height: 1;
  padding: 0 0.25rem;
}
.btn-close:hover {
  color: var(--color-text);
}

.panel-messages {
  flex: 1;
  overflow-y: auto;
  padding: 0.75rem;
  display: flex;
  flex-direction: column;
}
.messages-inner {
  margin-top: auto;
}

/* Streaming bubble — matches ChatMessage assistant style */
.chat-message {
  display: flex;
  margin-bottom: 0.75rem;
}
.role-assistant {
  justify-content: flex-start;
}
.streaming-bubble {
  max-width: 90%;
  padding: 0.75rem 1rem;
  border-radius: 16px;
  border-bottom-left-radius: 4px;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
}
.streaming-bubble .message-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.25rem;
}
.streaming-bubble .role-label {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--color-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.streaming-bubble .message-content {
  font-size: 0.95rem;
  line-height: 1.55;
  word-break: break-word;
}
.thinking-block {
  margin-bottom: 0.5rem;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  overflow: hidden;
}
.thinking-summary {
  padding: 0.25rem 0.5rem;
  font-size: 0.72rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--color-text-muted);
  cursor: pointer;
  user-select: none;
  list-style: none;
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: var(--color-bg-secondary);
}
.thinking-summary::-webkit-details-marker { display: none; }
.thinking-summary::before {
  content: "▶";
  font-size: 0.6rem;
  transition: transform 0.15s;
}
details[open] .thinking-summary::before {
  transform: rotate(90deg);
}
.thinking-text {
  margin: 0;
  padding: 0.5rem;
  font-size: 0.8rem;
  line-height: 1.5;
  color: var(--color-text-secondary);
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  background: var(--color-bg-secondary);
  border-top: 1px solid var(--color-border);
}
.typing-indicator {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--color-primary);
  animation: blink 1s infinite;
  margin-left: 4px;
  vertical-align: middle;
}
@keyframes blink {
  0%, 100% { opacity: 0.3; }
  50% { opacity: 1; }
}

/* Context pills */
.context-pills {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.25rem;
  padding: 0.35rem 0;
}
.context-pills-label {
  font-size: 0.7rem;
  color: var(--color-text-muted);
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.context-pill {
  display: inline-flex;
  align-items: center;
  gap: 0.1rem;
  background: var(--color-bg-secondary);
  border: 1px solid var(--color-border);
  border-radius: 10px;
  padding: 0.1rem 0.25rem 0.1rem 0.4rem;
  font-size: 0.75rem;
}
.context-pill-link {
  color: var(--color-primary);
  text-decoration: none;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.context-pill-link:hover {
  text-decoration: underline;
}
.context-pill-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 0.8rem;
  line-height: 1;
  padding: 0 0.1rem;
  color: var(--color-text-muted);
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.context-pill-btn:hover {
  background: var(--color-border);
}
.context-pill-btn.promote:hover {
  color: var(--color-primary);
}

/* Input wrapper */
.panel-input-wrapper {
  margin: 0 0.5rem 0.5rem;
}

/* Attached note */
.attached-note {
  padding: 0.2rem 0.5rem;
}
.attached-note-pill {
  display: inline-flex;
  align-items: center;
  gap: 0.2rem;
  background: var(--color-primary);
  color: #fff;
  border-radius: 10px;
  padding: 0.15rem 0.4rem;
  font-size: 0.75rem;
}
.attached-note-remove {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  font-size: 0.9rem;
  line-height: 1;
  padding: 0 0.1rem;
}
.attached-note-remove:hover {
  color: #fff;
}

/* Floating input */
.panel-input {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.5rem 0.5rem 0.75rem;
  background: var(--color-input-bar-bg);
  border-radius: 16px;
  box-shadow: 0 2px 8px var(--color-shadow);
}

/* Note picker */
.note-picker-wrapper {
  position: relative;
}
.btn-attach {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--color-input-bar-text);
  opacity: 0.6;
  padding: 0.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn-attach:hover {
  opacity: 1;
}
.btn-attach:disabled {
  opacity: 0.3;
  cursor: default;
}
.note-picker-dropdown {
  position: absolute;
  bottom: calc(100% + 8px);
  left: 0;
  width: 260px;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  box-shadow: 0 4px 16px var(--color-shadow);
  z-index: 10;
  overflow: hidden;
}
.panel-note-picker-search {
  width: 100%;
  padding: 0.45rem 0.65rem;
  border: none;
  border-bottom: 1px solid var(--color-border);
  background: transparent;
  color: var(--color-text);
  font-size: 0.85rem;
  outline: none;
  font-family: inherit;
  box-sizing: border-box;
}
.note-picker-results {
  max-height: 180px;
  overflow-y: auto;
}
.note-picker-item {
  padding: 0.4rem 0.65rem;
  cursor: pointer;
  font-size: 0.85rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.note-picker-item:hover {
  background: var(--color-bg-secondary);
}
.note-picker-empty {
  padding: 0.4rem 0.65rem;
  color: var(--color-text-muted);
  font-size: 0.8rem;
}
.panel-input textarea {
  flex: 1;
  resize: none;
  padding: 0.35rem 0.5rem;
  border: none;
  border-radius: 10px;
  font-family: inherit;
  font-size: 0.9rem;
  background: transparent;
  color: var(--color-input-bar-text);
  outline: none;
  max-height: 150px;
  overflow-y: auto;
}
.panel-input textarea::placeholder {
  color: var(--color-input-bar-placeholder);
}
.panel-input textarea:disabled {
  opacity: 0.5;
}
.btn-send {
  width: 30px;
  min-width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 1rem;
  flex-shrink: 0;
}
.btn-send:disabled {
  opacity: 0.35;
  cursor: default;
}

.empty-msg {
  color: var(--color-text-muted);
  font-size: 0.9rem;
  text-align: center;
  padding: 2rem 1rem;
}

@media (max-width: 480px) {
  .chat-panel {
    width: 100vw;
  }
}
</style>
