<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 { useToastStore } from "@/stores/toast";
import ChatPanel from "@/components/ChatPanel.vue";
import WorkspaceTaskPanel from "@/components/WorkspaceTaskPanel.vue";
import WorkspaceNoteEditor from "@/components/WorkspaceNoteEditor.vue";

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

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

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

const project = ref<Project | null>(null);
const chatPanelRef = ref<InstanceType<typeof ChatPanel> | null>(null);
const taskPanelRef = ref<InstanceType<typeof WorkspaceTaskPanel> | null>(null);
const noteEditorRef = ref<InstanceType<typeof WorkspaceNoteEditor> | 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(() => {
  return [
    panelOpen.value.tasks ? "minmax(0, 0.8fr)" : "0px",
    panelOpen.value.chat  ? "minmax(0, 1.1fr)" : "0px",
    panelOpen.value.notes ? "minmax(0, 1.1fr)" : "0px",
  ].join(" ");
});

// SSE watcher — auto-load notes/tasks when tool calls succeed
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;
        noteEditorRef.value?.reload();
      }
      if (
        tc.status === "success" && (
          ["create_milestone", "update_milestone"].includes(tc.function) ||
          (tc.function === "create_note" && tc.result?.data?.status) ||
          (tc.function === "update_note" && tc.result?.data?.status !== undefined)
        )
      ) {
        taskPanelRef.value?.reload();
      }
    }
    processedCount.value = calls.length;
  },
  { deep: true }
);

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

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

function prefill(text: string) {
  chatPanelRef.value?.prefill(text);
}

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 conv = await chatStore.createConversation();
    workspaceConvId = conv.id;
    isNewConv = true;
    await chatStore.fetchConversation(conv.id);
    localStorage.setItem(key, String(conv.id));
  }

  nextTick(() => chatPanelRef.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">{{ project?.goal ?? '' }}</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">
        <Transition name="panel-fade">
          <div v-if="panelOpen.tasks" class="panel-inner">
            <WorkspaceTaskPanel
              v-if="project"
              ref="taskPanelRef"
              :project-id="project.id"
            />
          </div>
        </Transition>
      </div>

      <!-- Center: Chat -->
      <div v-show="panelOpen.chat" class="ws-panel ws-panel-chat">
        <Transition name="panel-fade">
          <div v-if="panelOpen.chat" class="panel-inner panel-inner-chat">
            <!-- Quick chips (shown when conversation is empty) -->
            <div
              v-if="chatStore.currentConversation && !chatStore.currentConversation.messages.length && !chatStore.streaming"
              class="empty-chat-prompt"
            >
              <p class="empty-hint">What would you like to work on?</p>
              <div class="quick-chips">
                <button class="quick-chip" @click="prefill('Summarize the current status of this project')">📊 Project status</button>
                <button class="quick-chip" @click="prefill('Create a note about ')">📝 New note</button>
                <button class="quick-chip" @click="prefill('Add tasks for ')">✓ Add tasks</button>
              </div>
            </div>
            <ChatPanel
              ref="chatPanelRef"
              variant="full"
              :projectId="projectId"
              placeholder="Message the agent… (Enter to send)"
              class="ws-chat-panel"
            />
          </div>
        </Transition>
      </div>

      <!-- Right: Note Editor -->
      <div v-show="panelOpen.notes" class="ws-panel">
        <Transition name="panel-fade">
          <div v-if="panelOpen.notes" class="panel-inner">
            <WorkspaceNoteEditor
              v-if="project"
              ref="noteEditorRef"
              :project-id="project.id"
              :active-note-id="activeNoteId"
            />
          </div>
        </Transition>
      </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-size: 0.78rem;
  color: var(--color-text-muted);
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-style: italic;
}

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

.panel-inner {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-fade-enter-active,
.panel-fade-leave-active {
  transition: opacity 0.18s ease;
}
.panel-fade-enter-from,
.panel-fade-leave-to {
  opacity: 0;
}

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

.panel-inner-chat {
  position: relative;
}

.ws-chat-panel {
  flex: 1;
  min-height: 0;
}

.empty-chat-prompt {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  padding: 2rem 1rem;
  pointer-events: none;
  z-index: 1;
}
.empty-hint {
  margin: 0 0 1rem;
  color: var(--color-text-secondary);
  font-size: 0.9rem;
}
.quick-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  justify-content: center;
  pointer-events: auto;
}
.quick-chip {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: 20px;
  padding: 0.4rem 0.85rem;
  font-size: 0.82rem;
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: border-color 0.15s, color 0.15s, background 0.15s;
  font-family: inherit;
}
.quick-chip:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
  background: color-mix(in srgb, var(--color-primary) 5%, var(--color-surface));
}
</style>
