<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProjectsStore } from '@/stores/projects'
import { useDocumentsStore } from '@/stores/documents'
import Header from '@/components/layout/Header.vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import Button from '@/components/common/Button.vue'
import Modal from '@/components/common/Modal.vue'
import GraphView from '@/components/common/GraphView.vue'
import type { TreeNode } from '@/types'

const route = useRoute()
const router = useRouter()
const projectsStore = useProjectsStore()
const documentsStore = useDocumentsStore()

const showNewFolderModal = ref(false)
const showNewDocModal = ref(false)
const newFolderName = ref('')
const newDocName = ref('')
const selectedParentId = ref<string | null>(null)
const creating = ref(false)

// Feature 1: Edit project modal
const showEditProjectModal = ref(false)
const editProjectName = ref('')
const editProjectDesc = ref('')
const savingProject = ref(false)

// Phase 3: Graph & Export
const showGraphView = ref(false)
const showExportModal = ref(false)
const exportFormat = ref<'zip' | 'json'>('zip')
const exporting = ref(false)

// Feature 2: Folder picker
const folderPickerOpen = ref(false)
const folderPickerSelectedId = ref<string | null>(null)
const folderPickerExpanded = ref<Set<string>>(new Set())

onMounted(async () => {
  const projectId = route.params.id as string
  await projectsStore.fetchProject(projectId)
})

watch(() => route.params.id, async (newId) => {
  if (newId) {
    await projectsStore.fetchProject(newId as string)
  }
})

function openDocument(docId: string) {
  router.push(`/documents/${docId}`)
}

function emitCreateFolder() {
  selectedParentId.value = null
  showNewFolderModal.value = true
}

function emitCreateDocument() {
  selectedParentId.value = null
  showNewDocModal.value = true
  folderPickerSelectedId.value = null
  folderPickerOpen.value = false
}

async function createFolder() {
  if (!newFolderName.value.trim() || !projectsStore.currentProject) return

  creating.value = true
  try {
    await projectsStore.createFolder(
      projectsStore.currentProject.id,
      newFolderName.value.trim(),
      selectedParentId.value
    )
    showNewFolderModal.value = false
    newFolderName.value = ''
  } catch (e) {
    console.error('Failed to create folder:', e)
  } finally {
    creating.value = false
  }
}

async function createDocument() {
  if (!newDocName.value.trim() || !projectsStore.currentProject) return

  creating.value = true
  try {
    const doc = await documentsStore.createDocument(
      projectsStore.currentProject.id,
      newDocName.value.trim(),
      '',
      folderPickerSelectedId.value
    )
    showNewDocModal.value = false
    newDocName.value = ''
    folderPickerSelectedId.value = null
    folderPickerOpen.value = false
    // Refresh project tree
    await projectsStore.fetchProjectTree(projectsStore.currentProject.id)
    // Open the new document
    openDocument(doc.id)
  } catch (e) {
    console.error('Failed to create document:', e)
  } finally {
    creating.value = false
  }
}

// Feature 1: Edit project
function openEditProjectModal() {
  if (!projectsStore.currentProject) return
  editProjectName.value = projectsStore.currentProject.name
  editProjectDesc.value = projectsStore.currentProject.description || ''
  showEditProjectModal.value = true
}

async function saveProject() {
  if (!projectsStore.currentProject || !editProjectName.value.trim()) return
  savingProject.value = true
  try {
    await projectsStore.patchProject(projectsStore.currentProject.id, {
      name: editProjectName.value.trim(),
      description: editProjectDesc.value.trim() || undefined
    })
    showEditProjectModal.value = false
  } catch (e) {
    console.error('Failed to update project:', e)
  } finally {
    savingProject.value = false
  }
}

// Feature 2: Folder picker helpers
const folderOptions = computed(() => {
  return buildFlatFolders(projectsStore.treeNodes)
})

function buildFlatFolders(nodes: TreeNode[], depth = 0): Array<{ id: string; name: string; depth: number }> {
  const result: Array<{ id: string; name: string; depth: number }> = []
  for (const node of nodes) {
    if (node.type === 'folder') {
      result.push({ id: node.id, name: node.name, depth })
      if (node.children) {
        result.push(...buildFlatFolders(node.children, depth + 1))
      }
    }
  }
  return result
}

function toggleFolderPicker() {
  folderPickerOpen.value = !folderPickerOpen.value
  if (folderPickerOpen.value) {
    // auto-expand all so user can see everything
    const allIds = projectsStore.folders.map(f => f.id)
    folderPickerExpanded.value = new Set(allIds)
  }
}

function selectFolder(id: string) {
  folderPickerSelectedId.value = folderPickerSelectedId.value === id ? null : id
}

function clearFolderSelection() {
  folderPickerSelectedId.value = null
}

function getSelectedFolderName(): string {
  if (!folderPickerSelectedId.value) return 'Root (no folder)'
  const folder = projectsStore.folders.find(f => f.id === folderPickerSelectedId.value)
  return folder ? folder.name : 'Root (no folder)'
}

// Phase 3: Graph
function openGraphView() {
  showGraphView.value = true
}

// Phase 3: Export
function openExportModal() {
  showExportModal.value = true
}

async function handleExport() {
  if (!projectsStore.currentProject) return
  exporting.value = true
  try {
    const blob = await projectsStore.exportProject(projectsStore.currentProject.id, exportFormat.value)
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    const name = projectsStore.currentProject.name.replace(/[^a-z0-9]/gi, '_')
    a.href = url
    a.download = `${name}.${exportFormat.value}`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    showExportModal.value = false
  } catch (e) {
    console.error('Export failed:', e)
  } finally {
    exporting.value = false
  }
}
</script>

<template>
  <div class="layout">
    <Header />
    <div class="layout__body">
      <Sidebar
        @create-folder="emitCreateFolder"
        @create-document="emitCreateDocument"
      />
      <main class="layout__content">
        <div v-if="projectsStore.loading" class="loading">
          <div class="loading__spinner"></div>
          <p>Loading project...</p>
        </div>

        <div v-else-if="projectsStore.error" class="error">
          <p>{{ projectsStore.error }}</p>
          <Button variant="secondary" @click="router.push('/dashboard')">
            Back to Dashboard
          </Button>
        </div>

        <div v-else-if="projectsStore.currentProject" class="project">
          <div class="project__welcome">
            <div class="project__title-row">
              <h1 class="project__title">{{ projectsStore.currentProject.name }}</h1>
              <button class="edit-icon-btn" title="Edit project" @click="openEditProjectModal">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                </svg>
              </button>
            </div>
            <p v-if="projectsStore.currentProject.description" class="project__desc">
              {{ projectsStore.currentProject.description }}
            </p>
            <p class="project__hint">
              Select a document from the sidebar or create a new one to get started.
            </p>
            <div class="project__actions">
              <Button variant="secondary" @click="openGraphView">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="18" cy="5" r="3"/>
                  <circle cx="6" cy="12" r="3"/>
                  <circle cx="18" cy="19" r="3"/>
                  <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
                  <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
                </svg>
                View Graph
              </Button>
              <Button variant="secondary" @click="openExportModal">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                  <polyline points="7 10 12 15 17 10"/>
                  <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                Export
              </Button>
            </div>
          </div>
        </div>
      </main>
    </div>

    <!-- New Folder Modal -->
    <Modal :show="showNewFolderModal" title="Create New Folder" @close="showNewFolderModal = false">
      <form @submit.prevent="createFolder">
        <div class="form__field">
          <label for="folder-name" class="form__label">Folder Name</label>
          <input
            id="folder-name"
            v-model="newFolderName"
            type="text"
            class="form__input"
            placeholder="My Folder"
            autofocus
          />
        </div>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showNewFolderModal = false">Cancel</Button>
        <Button variant="primary" :loading="creating" @click="createFolder">Create Folder</Button>
      </template>
    </Modal>

    <!-- New Document Modal -->
    <Modal :show="showNewDocModal" title="Create New Document" @close="showNewDocModal = false">
      <form @submit.prevent="createDocument">
        <div class="form__field">
          <label for="doc-name" class="form__label">Document Title</label>
          <input
            id="doc-name"
            v-model="newDocName"
            type="text"
            class="form__input"
            placeholder="Untitled Document"
            autofocus
          />
        </div>
        <!-- Feature 2: Folder selector -->
        <div class="form__field">
          <label class="form__label">Folder (optional)</label>
          <div class="folder-picker">
            <button
              type="button"
              class="folder-picker__trigger"
              @click="toggleFolderPicker"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
              </svg>
              <span>{{ getSelectedFolderName() }}</span>
              <svg
                :class="['folder-picker__chevron', { 'folder-picker__chevron--open': folderPickerOpen }]"
                width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
              >
                <path d="m6 9 6 6 6-6"/>
              </svg>
            </button>
            <div v-if="folderPickerOpen" class="folder-picker__dropdown">
              <button
                type="button"
                class="folder-picker__option"
                :class="{ 'folder-picker__option--selected': !folderPickerSelectedId }"
                @click="clearFolderSelection"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                </svg>
                Root (no folder)
              </button>
              <button
                v-for="folder in folderOptions"
                :key="folder.id"
                type="button"
                class="folder-picker__option"
                :class="{ 'folder-picker__option--selected': folderPickerSelectedId === folder.id }"
                :style="{ paddingLeft: `${0.75 + folder.depth * 1}rem` }"
                @click="selectFolder(folder.id)"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
                </svg>
                {{ folder.name }}
              </button>
            </div>
          </div>
        </div>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showNewDocModal = false">Cancel</Button>
        <Button variant="primary" :loading="creating" @click="createDocument">Create Document</Button>
      </template>
    </Modal>

    <!-- Feature 1: Edit Project Modal -->
    <Modal :show="showEditProjectModal" title="Edit Project" @close="showEditProjectModal = false">
      <form @submit.prevent="saveProject">
        <div class="form__field">
          <label for="edit-proj-name" class="form__label">Project Name</label>
          <input
            id="edit-proj-name"
            v-model="editProjectName"
            type="text"
            class="form__input"
            placeholder="Project name"
            autofocus
          />
        </div>
        <div class="form__field">
          <label for="edit-proj-desc" class="form__label">Description</label>
          <textarea
            id="edit-proj-desc"
            v-model="editProjectDesc"
            class="form__input form__textarea"
            placeholder="Add a description..."
            rows="3"
          ></textarea>
        </div>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showEditProjectModal = false">Cancel</Button>
        <Button variant="primary" :loading="savingProject" @click="saveProject">Save</Button>
      </template>
    </Modal>

    <!-- Graph View Modal -->
    <Modal :show="showGraphView" title="" size="lg" @close="showGraphView = false">
      <GraphView
        v-if="projectsStore.currentProject"
        :project-id="projectsStore.currentProject.id"
        @close="showGraphView = false"
      />
    </Modal>

    <!-- Export Modal -->
    <Modal :show="showExportModal" title="Export Project" @close="showExportModal = false">
      <div class="form__field">
        <label class="form__label">Format</label>
        <div class="export-formats">
          <button
            :class="['export-format', { 'export-format--selected': exportFormat === 'zip' }]"
            @click="exportFormat = 'zip'"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
            </svg>
            <span>ZIP Archive</span>
            <small>Documents as .md files</small>
          </button>
          <button
            :class="['export-format', { 'export-format--selected': exportFormat === 'json' }]"
            @click="exportFormat = 'json'"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
              <path d="M8 13h2"/><path d="M8 17h2"/>
              <path d="M14 13h2"/><path d="M14 17h2"/>
            </svg>
            <span>JSON</span>
            <small>Full project with metadata</small>
          </button>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showExportModal = false">Cancel</Button>
        <Button variant="primary" :loading="exporting" @click="handleExport">Download</Button>
      </template>
    </Modal>
  </div>
</template>

<style scoped>
.layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.layout__body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.layout__content {
  flex: 1;
  overflow-y: auto;
  background: var(--bg-primary);
}

.loading,
.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  height: 100%;
  color: var(--text-secondary);
}

.loading__spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.project {
  padding: 2rem;
}

.project__welcome {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
  padding: 4rem 2rem;
}

.project__title {
  margin: 0;
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
}

.project__title-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
}

.edit-icon-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  background: none;
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.edit-icon-btn:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border-color: var(--accent);
}

.project__desc {
  margin: 0.75rem 0 0;
  font-size: 1rem;
  color: var(--text-secondary);
  line-height: 1.5;
}

.project__hint {
  margin: 1.5rem 0 0;
  font-size: 0.9375rem;
  color: var(--text-secondary);
}

.project__actions {
  display: flex;
  justify-content: center;
  gap: 0.75rem;
  margin-top: 1.5rem;
}

/* Form styles */
.form__field {
  margin-bottom: 1.25rem;
}

.form__field:last-child {
  margin-bottom: 0;
}

.form__label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
}

.form__input {
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.9375rem;
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.15s, box-shadow 0.15s;
  box-sizing: border-box;
}

.form__input::placeholder {
  color: var(--text-secondary);
}

.form__input:focus {
  border-color: var(--accent);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form__textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
  line-height: 1.5;
}

/* Folder Picker */
.folder-picker {
  position: relative;
}

.folder-picker__trigger {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.9375rem;
  color: var(--text-primary);
  cursor: pointer;
  text-align: left;
  transition: border-color 0.15s;
}

.folder-picker__trigger:hover {
  border-color: var(--accent);
}

.folder-picker__trigger span {
  flex: 1;
}

.folder-picker__chevron {
  transition: transform 0.15s;
  color: var(--text-secondary);
}

.folder-picker__chevron--open {
  transform: rotate(180deg);
}

.folder-picker__dropdown {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 50;
  max-height: 240px;
  overflow-y: auto;
}

.folder-picker__option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  padding: 0.625rem 0.75rem;
  background: none;
  border: none;
  font-size: 0.875rem;
  color: var(--text-primary);
  cursor: pointer;
  text-align: left;
  transition: background 0.1s;
}

.folder-picker__option:hover {
  background: var(--bg-tertiary);
}

.folder-picker__option--selected {
  background: rgba(99, 102, 241, 0.1);
  color: var(--accent);
}

/* Export Modal Styles */
.export-formats {
  display: flex;
  gap: 0.75rem;
}

.export-format {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1.25rem 1rem;
  background: var(--bg-secondary);
  border: 2px solid var(--border);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.15s;
  color: var(--text-secondary);
}

.export-format:hover {
  border-color: var(--accent);
  color: var(--text-primary);
}

.export-format--selected {
  border-color: var(--accent);
  background: rgba(99, 102, 241, 0.08);
  color: var(--accent);
}

.export-format span {
  font-size: 0.9375rem;
  font-weight: 600;
  color: var(--text-primary);
}

.export-format small {
  font-size: 0.75rem;
  color: var(--text-secondary);
}
</style>
