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

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

const editTitle = ref('')
const editContent = ref('')
const showTagModal = ref(false)
const newTagName = ref('')
const newTagColor = ref('#6366f1')
const saveTimeout = ref<ReturnType<typeof setTimeout> | null>(null)

onMounted(async () => {
  const docId = route.params.id as string
  await documentsStore.fetchDocument(docId)
  await documentsStore.fetchTags()
  
  if (documentsStore.currentDocument) {
    editTitle.value = documentsStore.currentDocument.title
    editContent.value = documentsStore.currentDocument.content
  }
})

watch(() => route.params.id, async (newId) => {
  if (newId) {
    await documentsStore.fetchDocument(newId as string)
    if (documentsStore.currentDocument) {
      editTitle.value = documentsStore.currentDocument.title
      editContent.value = documentsStore.currentDocument.content
    }
  }
})

watch(() => documentsStore.currentDocument, (doc) => {
  if (doc) {
    editTitle.value = doc.title
    editContent.value = doc.content
  }
})

function handleContentChange() {
  // Auto-save with debounce
  if (saveTimeout.value) {
    clearTimeout(saveTimeout.value)
  }
  saveTimeout.value = setTimeout(() => {
    saveContent()
  }, 1500)
}

async function saveContent() {
  if (!documentsStore.currentDocument) return
  await documentsStore.updateDocumentContent(
    documentsStore.currentDocument.id,
    editContent.value
  )
}

async function updateTitle() {
  if (!documentsStore.currentDocument || !editTitle.value.trim()) return
  await documentsStore.updateDocument(
    documentsStore.currentDocument.id,
    editTitle.value.trim()
  )
}

async function removeTag(tagId: string) {
  if (!documentsStore.currentDocument) return
  await documentsStore.removeTag(documentsStore.currentDocument.id, tagId)
}

async function createAndAssignTag() {
  if (!newTagName.value.trim() || !documentsStore.currentDocument) return
  
  const tag = await documentsStore.createTag(newTagName.value.trim(), newTagColor.value)
  const currentTagIds = documentsStore.currentDocument.tags.map(t => t.id)
  await documentsStore.assignTags(documentsStore.currentDocument.id, [...currentTagIds, tag.id])
  
  showTagModal.value = false
  newTagName.value = ''
  newTagColor.value = '#6366f1'
}

async function goBack() {
  if (documentsStore.currentDocument) {
    router.push(`/projects/${documentsStore.currentDocument.project_id}`)
  } else {
    router.push('/dashboard')
  }
}

const tagColors = [
  '#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f97316',
  '#eab308', '#22c55e', '#10b981', '#14b8a6', '#06b6d4'
]
</script>

<template>
  <div class="layout">
    <Header />
    <div class="layout__body">
      <main class="layout__content">
        <div v-if="documentsStore.loading" class="loading">
          <div class="loading__spinner"></div>
          <p>Loading document...</p>
        </div>

        <div v-else-if="documentsStore.error" class="error">
          <p>{{ documentsStore.error }}</p>
          <Button variant="secondary" @click="goBack">Go Back</Button>
        </div>

        <div v-else-if="documentsStore.currentDocument" class="doc-view">
          <div class="doc-view__toolbar">
            <button class="doc-view__back" @click="goBack">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="m15 18-6-6 6-6"/>
              </svg>
              Back
            </button>

            <div class="doc-view__saving" v-if="documentsStore.saving">
              <div class="doc-view__saving-dot"></div>
              Saving...
            </div>
            <div class="doc-view__saved" v-else>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="20 6 9 17 4 12"/>
              </svg>
              Saved
            </div>
          </div>

          <div class="doc-view__header">
            <input
              v-model="editTitle"
              type="text"
              class="doc-view__title"
              placeholder="Untitled Document"
              @blur="updateTitle"
              @keyup.enter="($event.target as HTMLInputElement).blur()"
            />
          </div>

          <div class="doc-view__tags">
            <span
              v-for="tag in documentsStore.currentDocument.tags"
              :key="tag.id"
              class="doc-view__tag"
              :style="{ backgroundColor: tag.color + '20', color: tag.color, borderColor: tag.color }"
            >
              {{ tag.name }}
              <button class="doc-view__tag-remove" @click="removeTag(tag.id)">×</button>
            </span>
            <button class="doc-view__add-tag" @click="showTagModal = true">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="12" y1="5" x2="12" y2="19"/>
                <line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              Add Tag
            </button>
          </div>

          <div class="doc-view__editor">
            <textarea
              v-model="editContent"
              class="doc-view__textarea"
              placeholder="Start writing in Markdown..."
              @input="handleContentChange"
            ></textarea>
          </div>
        </div>
      </main>
    </div>

    <!-- Tag Modal -->
    <Modal :show="showTagModal" title="Add Tag" @close="showTagModal = false">
      <div class="form__field">
        <label for="tag-name" class="form__label">Tag Name</label>
        <input
          id="tag-name"
          v-model="newTagName"
          type="text"
          class="form__input"
          placeholder="backend"
          autofocus
        />
      </div>
      <div class="form__field">
        <label class="form__label">Color</label>
        <div class="color-picker">
          <button
            v-for="color in tagColors"
            :key="color"
            :class="['color-picker__option', { 'color-picker__option--selected': color === newTagColor }]"
            :style="{ backgroundColor: color }"
            @click="newTagColor = color"
          ></button>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showTagModal = false">Cancel</Button>
        <Button variant="primary" @click="createAndAssignTag">Add Tag</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);
  }
}

.doc-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.doc-view__toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.doc-view__back {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: none;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__back:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.doc-view__saving {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8125rem;
  color: var(--text-secondary);
}

.doc-view__saving-dot {
  width: 8px;
  height: 8px;
  background: var(--accent);
  border-radius: 50%;
  animation: pulse 1s ease-in-out infinite;
}

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

.doc-view__saved {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  font-size: 0.8125rem;
  color: #22c55e;
}

.doc-view__header {
  margin-bottom: 1rem;
}

.doc-view__title {
  width: 100%;
  padding: 0;
  background: none;
  border: none;
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
  outline: none;
}

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

.doc-view__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border);
}

.doc-view__tag {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.25rem 0.625rem;
  border: 1px solid;
  border-radius: 9999px;
  font-size: 0.8125rem;
  font-weight: 500;
}

.doc-view__tag-remove {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  padding: 0;
  background: none;
  border: none;
  border-radius: 50%;
  font-size: 1rem;
  line-height: 1;
  cursor: pointer;
  opacity: 0.7;
}

.doc-view__tag-remove:hover {
  opacity: 1;
}

.doc-view__add-tag {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.25rem 0.625rem;
  background: var(--bg-secondary);
  border: 1px dashed var(--border);
  border-radius: 9999px;
  font-size: 0.8125rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__add-tag:hover {
  border-color: var(--accent);
  color: var(--accent);
}

.doc-view__editor {
  flex: 1;
}

.doc-view__textarea {
  width: 100%;
  min-height: 400px;
  padding: 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-family: 'JetBrains Mono', 'Fira Code', monospace;
  font-size: 0.9375rem;
  line-height: 1.7;
  color: var(--text-primary);
  resize: vertical;
  outline: none;
  transition: border-color 0.15s;
  box-sizing: border-box;
}

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

.doc-view__textarea:focus {
  border-color: var(--accent);
}

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

.color-picker {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.color-picker__option {
  width: 32px;
  height: 32px;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.1s, border-color 0.1s;
}

.color-picker__option:hover {
  transform: scale(1.1);
}

.color-picker__option--selected {
  border-color: var(--text-primary);
}
</style>
