<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
import { useRoute } from "vue-router";
import { apiGet } from "@/api/client";
import { useChatStore } from "@/stores/chat";
import { useSettingsStore } from "@/stores/settings";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import ChatMessage from "@/components/ChatMessage.vue";
import ToolCallCard from "@/components/ToolCallCard.vue";
import ToolConfirmCard from "@/components/ToolConfirmCard.vue";
import WorkspaceTaskPanel from "@/components/WorkspaceTaskPanel.vue";
import WorkspaceNoteEditor from "@/components/WorkspaceNoteEditor.vue";

const route = useRoute();
const chatStore = useChatStore();
const settingsStore = useSettingsStore();
const toast = useToastStore();

const projectId = computed(() => Number(route.params.projectId));

interface Project {
  id: number;
  title: string;
}

const project = ref<Project | null>(null);
const messageInput = ref("");
const messagesEl = ref<HTMLElement | null>(null);
const inputEl = ref<HTMLTextAreaElement | null>(null);
const taskPanelRef = ref<InstanceType<typeof WorkspaceTaskPanel> | null>(null);
const activeNoteId = ref<number | null>(null);
let workspaceConvId: number | null = null;
let isNewConv = false;

function _storageKey(pid: number) {
  return `workspace_conv_${pid}`;
}

// Panel collapse state — persisted per project
function _panelKey(pid: number) { return `workspace_panels_${pid}`; }

function _loadPanelState(pid: number) {
  try {
    const raw = localStorage.getItem(_panelKey(pid));
    if (raw) {
      const saved = JSON.parse(raw);
      // Ensure at least one panel is open after restore
      if (!saved.tasks && !saved.chat && !saved.notes) saved.chat = true;
      return saved as { tasks: boolean; chat: boolean; notes: boolean };
    }
  } catch { /* ignore */ }
  return { tasks: true, chat: true, notes: true };
}

const panelOpen = ref({ tasks: true, chat: true, notes: true });

const gridColumns = computed(() => {
  const cols = [
    panelOpen.value.tasks ? "1fr" : "0px",
    panelOpen.value.chat ? "1fr" : "0px",
    panelOpen.value.notes ? "1fr" : "0px",
  ];
  return cols.join(" ");
});

// SSE watcher
const processedCount = ref(0);

watch(
  () => chatStore.streamingToolCalls,
  (calls) => {
    for (let i = processedCount.value; i < calls.length; i++) {
      const tc = calls[i];
      if (
        ["create_note", "update_note"].includes(tc.function) &&
        tc.status === "success" &&
        tc.result?.data?.id
      ) {
        activeNoteId.value = tc.result.data.id as number;
      }
      if (
        ["create_task", "update_task"].includes(tc.function) &&
        tc.status === "success"
      ) {
        taskPanelRef.value?.reload();
      }
    }
    processedCount.value = calls.length;
  },
  { deep: true }
);

watch(
  () => chatStore.streaming,
  (s) => {
    if (!s) {
      processedCount.value = 0;
      scrollToBottom();
    }
  }
);

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

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

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

function togglePanel(panel: keyof typeof panelOpen.value) {
  const open = panelOpen.value;
  const openCount = [open.tasks, open.chat, open.notes].filter(Boolean).length;
  if (open[panel] && openCount <= 1) return;
  panelOpen.value[panel] = !panelOpen.value[panel];
  localStorage.setItem(_panelKey(projectId.value), JSON.stringify(panelOpen.value));
}

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

  messageInput.value = "";
  resetTextareaHeight();

  await chatStore.sendMessage(
    content,
    undefined,
    undefined,
    true,
    undefined,
    undefined,
    projectId.value,
    projectId.value,
  );
  scrollToBottom();
  nextTick(() => inputEl.value?.focus());
}

function onInputKeydown(e: KeyboardEvent) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
  if (e.key === "Escape") {
    // Prevent App.vue from navigating home when textarea is focused
    e.stopPropagation();
    inputEl.value?.blur();
  }
}

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

onMounted(async () => {
  // Restore panel state
  panelOpen.value = _loadPanelState(projectId.value);

  // Load project info
  try {
    project.value = await apiGet<Project>(`/api/projects/${projectId.value}`);
  } catch {
    toast.show("Failed to load project", "error");
  }

  const key = _storageKey(projectId.value);
  const storedId = localStorage.getItem(key);

  if (storedId) {
    // Try to reuse the existing workspace conversation
    const existingId = Number(storedId);
    try {
      await chatStore.fetchConversation(existingId);
      workspaceConvId = existingId;
      isNewConv = false;
      chatStore.reconnectIfGenerating(existingId);
    } catch {
      // Conversation was deleted — create a fresh one
      localStorage.removeItem(key);
    }
  }

  if (workspaceConvId === null) {
    // Create a new workspace conversation and persist its ID
    const title = project.value ? `${project.value.title} — Workspace` : "Workspace";
    const conv = await chatStore.createConversation(title);
    workspaceConvId = conv.id;
    isNewConv = true;
    await chatStore.fetchConversation(conv.id);
    localStorage.setItem(key, String(conv.id));
  }

  nextTick(() => inputEl.value?.focus());
});

onUnmounted(async () => {
  // Only delete if we created a brand-new conversation this session and it's still empty
  if (workspaceConvId !== null && isNewConv) {
    const conv = chatStore.conversations.find((c) => c.id === workspaceConvId);
    if (conv && conv.message_count === 0) {
      await chatStore.deleteConversation(workspaceConvId);
      localStorage.removeItem(_storageKey(projectId.value));
    }
  }
});
</script>

<template>
  <div class="workspace-root">
    <!-- Header -->
    <header class="ws-header">
      <router-link :to="project ? `/projects/${project.id}` : '/projects'" class="ws-back">
        ← {{ project?.title ?? "Project" }}
      </router-link>
      <span class="ws-title">Workspace</span>
      <div class="ws-panel-toggles">
        <button
          :class="['panel-toggle', { active: panelOpen.tasks }]"
          title="Toggle Tasks panel"
          @click="togglePanel('tasks')"
        >
          Tasks
        </button>
        <button
          :class="['panel-toggle', { active: panelOpen.chat }]"
          title="Toggle Chat panel"
          @click="togglePanel('chat')"
        >
          Chat
        </button>
        <button
          :class="['panel-toggle', { active: panelOpen.notes }]"
          title="Toggle Notes panel"
          @click="togglePanel('notes')"
        >
          Notes
        </button>
      </div>
    </header>

    <!-- Three-panel body -->
    <div class="ws-body" :style="{ gridTemplateColumns: gridColumns }">

      <!-- Left: Tasks -->
      <div v-show="panelOpen.tasks" class="ws-panel">
        <WorkspaceTaskPanel
          v-if="project"
          ref="taskPanelRef"
          :project-id="project.id"
        />
      </div>

      <!-- Center: Chat -->
      <div v-show="panelOpen.chat" class="ws-panel ws-chat-panel">
        <div class="chat-messages" ref="messagesEl">
          <template v-if="chatStore.currentConversation">
            <ChatMessage
              v-for="msg in chatStore.currentConversation.messages"
              :key="msg.id"
              :message="msg"
            />
          </template>

          <!-- Streaming bubble -->
          <div v-if="chatStore.streaming" class="chat-message role-assistant">
            <div class="message-bubble streaming-bubble">
              <div class="message-header">
                <span class="role-label">{{ settingsStore.assistantName }}</span>
              </div>
              <div v-if="chatStore.streamingToolCalls.length" class="streaming-tool-calls">
                <ToolCallCard
                  v-for="(tc, i) in chatStore.streamingToolCalls"
                  :key="i"
                  :tool-call="tc"
                />
              </div>
              <ToolConfirmCard
                v-if="chatStore.streamingPendingTool"
                :pending-tool="chatStore.streamingPendingTool"
                @accept="chatStore.confirmTool(true)"
                @decline="chatStore.confirmTool(false)"
              />
              <div v-if="chatStore.streamingStatus" class="streaming-status-line">
                <span class="streaming-status-dot"></span>
                {{ chatStore.streamingStatus }}
              </div>
              <details
                v-if="chatStore.streamingThinking"
                class="thinking-block"
                :open="!chatStore.streamingContent"
              >
                <summary class="thinking-summary">Reasoning</summary>
                <pre class="thinking-text">{{ chatStore.streamingThinking }}</pre>
              </details>
              <div class="message-content prose" v-html="streamingRendered"></div>
              <span
                v-if="!chatStore.streamingStatus && !chatStore.streamingThinking"
                class="typing-indicator"
              ></span>
            </div>
          </div>

          <!-- Queued messages — shown as pending bubbles -->
          <template v-if="chatStore.queuedMessages.length">
            <div
              v-for="(q, i) in chatStore.queuedMessages"
              :key="`queued-${i}`"
              class="ws-message role-user queued-message"
            >
              <div class="message-bubble queued-bubble">
                <div class="queued-badge">Queued</div>
                <div class="message-content">{{ q.content }}</div>
              </div>
            </div>
            <div class="queued-clear-row">
              <button class="queued-clear-btn" @click="chatStore.clearQueue()" aria-label="Cancel queued messages">
                Cancel {{ chatStore.queuedMessages.length }} queued
              </button>
            </div>
          </template>

          <p
            v-if="chatStore.currentConversation && !chatStore.currentConversation.messages.length && !chatStore.streaming"
            class="empty-chat-msg"
          >
            Ask the agent to create notes or tasks for this project.
          </p>
        </div>

        <div class="chat-input-area">
          <textarea
            ref="inputEl"
            v-model="messageInput"
            class="chat-input"
            :placeholder="chatStore.streaming ? 'Type to queue next message… (Enter to queue)' : 'Message the agent… (Enter to send)'"
            rows="1"
            @keydown="onInputKeydown"
            @input="autoResize"
          ></textarea>
          <button
            v-if="chatStore.streaming"
            class="btn-abort"
            title="Stop generation"
            @click="chatStore.cancelGeneration()"
          >
            ■ Stop
          </button>
          <button
            v-else
            class="btn-send"
            :disabled="!messageInput.trim()"
            @click="sendMessage"
          >
            Send
          </button>
        </div>
      </div>

      <!-- Right: Note Editor -->
      <div v-show="panelOpen.notes" class="ws-panel">
        <WorkspaceNoteEditor
          v-if="project"
          :project-id="project.id"
          :active-note-id="activeNoteId"
        />
      </div>

    </div>
  </div>
</template>

<style scoped>
.workspace-root {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: var(--color-bg);
}

/* Header */
.ws-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  height: 44px;
  padding: 0 1rem;
  border-bottom: 1px solid var(--color-border);
  background: var(--color-surface);
  flex-shrink: 0;
  z-index: 10;
}

.ws-back {
  color: var(--color-primary);
  text-decoration: none;
  font-size: 0.875rem;
  white-space: nowrap;
}
.ws-back:hover {
  text-decoration: underline;
}

.ws-title {
  font-weight: 600;
  font-size: 0.9rem;
  color: var(--color-text-muted);
  flex: 1;
}

.ws-panel-toggles {
  display: flex;
  gap: 0.3rem;
}

.panel-toggle {
  background: none;
  border: 1px solid var(--color-border);
  border-radius: 5px;
  padding: 0.2rem 0.6rem;
  font-size: 0.78rem;
  cursor: pointer;
  color: var(--color-text-muted);
  transition: all 0.15s;
}

.panel-toggle.active {
  background: color-mix(in srgb, var(--color-primary) 12%, transparent);
  border-color: var(--color-primary);
  color: var(--color-primary);
}

/* Three-panel layout */
.ws-body {
  display: grid;
  flex: 1;
  overflow: hidden;
  transition: grid-template-columns 0.2s ease;
}

.ws-panel {
  overflow: hidden;
  min-width: 0;
}

/* Chat panel */
.ws-chat-panel {
  display: flex;
  flex-direction: column;
  border-left: 1px solid var(--color-border);
  border-right: 1px solid var(--color-border);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

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

.chat-input-area {
  display: flex;
  gap: 0.5rem;
  padding: 0.6rem;
  border-top: 1px solid var(--color-border);
  flex-shrink: 0;
}

.chat-input {
  flex: 1;
  resize: none;
  background: var(--color-input-bg, var(--color-bg));
  border: 1px solid var(--color-border);
  border-radius: 6px;
  padding: 0.4rem 0.6rem;
  font-size: 0.875rem;
  font-family: inherit;
  color: var(--color-text);
  line-height: 1.5;
  overflow-y: hidden;
}
.chat-input:focus {
  outline: none;
  border-color: var(--color-primary);
}

.btn-send {
  background: var(--color-primary);
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 0.4rem 0.9rem;
  font-size: 0.875rem;
  cursor: pointer;
  align-self: flex-end;
}
.btn-send:disabled {
  opacity: 0.4;
  cursor: default;
}

.btn-abort {
  background: none;
  color: var(--color-danger, #e74c3c);
  border: 1px solid var(--color-danger, #e74c3c);
  border-radius: 6px;
  padding: 0.4rem 0.9rem;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
  align-self: flex-end;
  white-space: nowrap;
}
.btn-abort:hover {
  background: var(--color-danger, #e74c3c);
  color: #fff;
}

/* Streaming indicators (mirror ChatView) */
.chat-message {
  display: flex;
}
.role-assistant {
  justify-content: flex-start;
}
.message-bubble {
  max-width: 85%;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: 10px;
  padding: 0.65rem 0.85rem;
}
.message-header {
  margin-bottom: 0.3rem;
}
.role-label {
  font-size: 0.72rem;
  font-weight: 600;
  color: var(--color-primary);
  text-transform: uppercase;
  letter-spacing: 0.04em;
}
.streaming-tool-calls {
  margin-bottom: 0.4rem;
}
.streaming-status-line {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.8rem;
  color: var(--color-text-muted);
  margin-bottom: 0.3rem;
}
.streaming-status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--color-primary);
  animation: pulse 1s infinite;
}
.typing-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--color-primary);
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

.message-content :deep(p) { margin: 0 0 0.5em; }
.message-content :deep(p:last-child) { margin-bottom: 0; }

.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;
}
.queued-bubble {
  background: var(--color-bg-secondary) !important;
  border: 1px dashed var(--color-border) !important;
  opacity: 0.7;
}
.queued-badge {
  font-size: 0.7rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--color-text-muted);
  margin-bottom: 0.25rem;
}
.queued-clear-row {
  display: flex;
  justify-content: flex-end;
  padding-right: 0.5rem;
}
.queued-clear-btn {
  background: none;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm, 6px);
  cursor: pointer;
  color: var(--color-text-muted);
  font-size: 0.78rem;
  padding: 0.2rem 0.6rem;
  font-family: inherit;
}
.queued-clear-btn:hover {
  color: var(--color-danger, #e74c3c);
  border-color: var(--color-danger, #e74c3c);
}
</style>
