<script setup lang="ts">
import { ref, onMounted, watch } 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'

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)

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

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
}

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(),
      '',
      selectedParentId.value
    )
    showNewDocModal.value = false
    newDocName.value = ''
    // 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
  }
}

// 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">
            <h1 class="project__title">{{ projectsStore.currentProject.name }}</h1>
            <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>
      </form>
      <template #footer>
        <Button variant="secondary" @click="showNewDocModal = false">Cancel</Button>
        <Button variant="primary" :loading="creating" @click="createDocument">Create Document</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__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);
}

/* 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>
