<script setup lang="ts">
import { onMounted, ref, computed, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useChatStore } from "@/stores/chat";
import { renderMarkdown } from "@/utils/markdown";
import ChatMessage from "@/components/ChatMessage.vue";

const route = useRoute();
const router = useRouter();
const store = useChatStore();

const messageInput = ref("");
const messagesEl = ref<HTMLElement | null>(null);
const sending = ref(false);
const summarizing = ref(false);

const convId = computed(() => {
  const id = route.params.id;
  return id ? Number(id) : null;
});

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

onMounted(async () => {
  await store.fetchConversations();
  if (convId.value) {
    await store.fetchConversation(convId.value);
  }
});

watch(convId, async (newId) => {
  if (newId) {
    await store.fetchConversation(newId);
    scrollToBottom();
  } else {
    store.currentConversation = null;
  }
});

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

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

async function selectConversation(id: number) {
  router.push(`/chat/${id}`);
}

async function newConversation() {
  const conv = await store.createConversation();
  router.push(`/chat/${conv.id}`);
}

async function removeConversation(id: number) {
  await store.deleteConversation(id);
  if (convId.value === id) {
    router.push("/chat");
  }
}

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

  // Auto-create conversation if none selected
  if (!store.currentConversation) {
    const conv = await store.createConversation();
    await store.fetchConversation(conv.id);
    router.push(`/chat/${conv.id}`);
  }

  sending.value = true;
  messageInput.value = "";
  scrollToBottom();

  await store.sendMessage(content);
  sending.value = false;

  // Refresh conversation list to show updated title/timestamps
  store.fetchConversations();
  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");
  }
}

async function handleSummarize() {
  if (!store.currentConversation || summarizing.value) return;
  summarizing.value = true;
  try {
    await store.summarizeAsNote(store.currentConversation.id);
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Conversation summarized and saved as note");
  } catch {
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Failed to summarize", "error");
  } finally {
    summarizing.value = false;
  }
}

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

<template>
  <main class="chat-page">
    <aside class="chat-sidebar">
      <button class="btn-new-conv" @click="newConversation">
        + New Chat
      </button>
      <div class="conv-list">
        <div
          v-for="conv in store.conversations"
          :key="conv.id"
          class="conv-item"
          :class="{ active: convId === conv.id }"
          @click="selectConversation(conv.id)"
        >
          <span class="conv-title">{{ conv.title || "Untitled" }}</span>
          <button
            class="btn-delete-conv"
            @click.stop="removeConversation(conv.id)"
            title="Delete conversation"
          >
            &times;
          </button>
        </div>
        <p v-if="!store.conversations.length" class="empty-msg">
          No conversations yet
        </p>
      </div>
    </aside>

    <section class="chat-main">
      <template v-if="store.currentConversation">
        <div class="chat-header">
          <h2>{{ store.currentConversation.title || "New Chat" }}</h2>
          <button
            v-if="store.currentConversation.messages.length"
            class="btn-summarize"
            @click="handleSummarize"
            :disabled="summarizing || store.streaming"
          >
            {{ summarizing ? "Summarizing..." : "Summarize as Note" }}
          </button>
        </div>

        <div ref="messagesEl" class="messages-container">
          <ChatMessage
            v-for="msg in store.currentConversation.messages"
            :key="msg.id"
            :message="msg"
            @save-as-note="handleSaveAsNote"
          />
          <div v-if="store.streaming" class="chat-message role-assistant streaming">
            <div class="message-header">
              <span class="role-label">Assistant</span>
            </div>
            <div class="message-content prose" v-html="streamingRendered"></div>
            <span class="typing-indicator"></span>
          </div>
          <p
            v-if="!store.currentConversation.messages.length && !store.streaming"
            class="empty-msg"
          >
            Send a message to start the conversation.
          </p>
        </div>

        <div class="input-area">
          <textarea
            v-model="messageInput"
            @keydown="onInputKeydown"
            placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
            :disabled="store.streaming"
            rows="2"
          ></textarea>
          <button
            class="btn-send"
            @click="sendMessage"
            :disabled="!messageInput.trim() || store.streaming"
          >
            Send
          </button>
        </div>
      </template>

      <div v-else class="no-conversation">
        <p>Select a conversation or start a new chat.</p>
        <button class="btn-new-conv" @click="newConversation">
          + New Chat
        </button>
      </div>
    </section>
  </main>
</template>

<style scoped>
.chat-page {
  display: flex;
  height: calc(100vh - 49px);
  overflow: hidden;
}

.chat-sidebar {
  width: 260px;
  min-width: 200px;
  border-right: 1px solid var(--color-border);
  display: flex;
  flex-direction: column;
  background: var(--color-bg-secondary);
}

.btn-new-conv {
  margin: 0.75rem;
  padding: 0.5rem;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
}
.btn-new-conv:hover {
  opacity: 0.9;
}

.conv-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 0.5rem;
}

.conv-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 0.25rem;
}
.conv-item:hover {
  background: var(--color-bg-card);
}
.conv-item.active {
  background: var(--color-primary);
  color: #fff;
}
.conv-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.9rem;
}
.btn-delete-conv {
  background: none;
  border: none;
  color: var(--color-text-muted);
  cursor: pointer;
  font-size: 1.2rem;
  padding: 0 0.25rem;
  line-height: 1;
}
.conv-item.active .btn-delete-conv {
  color: rgba(255, 255, 255, 0.7);
}
.btn-delete-conv:hover {
  color: var(--color-danger, #e74c3c);
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--color-border);
}
.chat-header h2 {
  margin: 0;
  font-size: 1.1rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.btn-summarize {
  padding: 0.3rem 0.75rem;
  background: var(--color-bg-secondary);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
  white-space: nowrap;
}
.btn-summarize:hover:not(:disabled) {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.btn-summarize:disabled {
  opacity: 0.6;
  cursor: default;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.streaming {
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 0.75rem 1rem;
  background: var(--color-bg-card);
  margin-bottom: 0.5rem;
}
.streaming .message-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.25rem;
}
.streaming .role-label {
  font-size: 0.8rem;
  font-weight: 600;
  color: var(--color-text-muted);
  text-transform: uppercase;
}
.streaming .message-content {
  font-size: 0.95rem;
  line-height: 1.5;
  word-break: break-word;
}

.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; }
}

.input-area {
  display: flex;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-top: 1px solid var(--color-border);
  background: var(--color-bg-secondary);
}
.input-area textarea {
  flex: 1;
  resize: none;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  font-family: inherit;
  font-size: 0.95rem;
  background: var(--color-bg);
  color: var(--color-text);
}
.input-area textarea:focus {
  outline: none;
  border-color: var(--color-primary);
}
.btn-send {
  padding: 0.5rem 1.25rem;
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  align-self: flex-end;
}
.btn-send:disabled {
  opacity: 0.5;
  cursor: default;
}

.no-conversation {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  color: var(--color-text-muted);
}

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

@media (max-width: 640px) {
  .chat-sidebar {
    width: 200px;
    min-width: 160px;
  }
}
</style>
