<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'

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)

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

/* 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);
}
</style>
