<template>
  <div class="flex h-full w-full min-h-[500px] border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900 shadow-sm relative isolate overflow-hidden">

    <div
        class="flex flex-col border-r border-gray-200 dark:border-gray-800 bg-gray-50/80 dark:bg-gray-900/50 transition-all duration-300"
        :class="selectedPage ? 'w-64 hidden md:flex shrink-0' : 'w-full'"
    >
      <div class="flex items-center justify-between px-3 py-3 border-b border-gray-200 dark:border-gray-800 shrink-0">
        <span class="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-1">
          <UIcon name="i-heroicons-list-bullet" class="w-3 h-3" />
          Inhalte
        </span>
        <UTooltip text="Neue Notiz erstellen">
          <UButton size="2xs" color="primary" variant="ghost" icon="i-heroicons-plus" @click="isCreateModalOpen = true" />
        </UTooltip>
      </div>

      <div class="flex-1 overflow-y-auto p-2 space-y-1 custom-scrollbar">
        <div v-if="loadingList" class="space-y-2 pt-2">
          <USkeleton class="h-8 w-full" />
          <USkeleton class="h-8 w-full" />
        </div>

        <template v-else-if="pages.length">
          <div
              v-for="page in pages"
              :key="page.id"
              class="flex items-center gap-2 px-2.5 py-2 rounded-md cursor-pointer text-sm transition-all border border-transparent"
              :class="selectedPage?.id === page.id ? 'bg-white dark:bg-gray-800 text-primary-600 shadow-sm border-gray-200 dark:border-gray-700 font-medium' : 'text-gray-600 hover:bg-white dark:hover:bg-gray-800 hover:shadow-sm'"
              @click="selectPage(page.id)"
          >
            <UIcon :name="page.isFolder ? 'i-heroicons-folder' : 'i-heroicons-document-text'" class="w-4 h-4 shrink-0" />
            <span class="truncate flex-1">{{ page.title }}</span>
          </div>
        </template>

        <div v-else class="flex flex-col items-center justify-center py-12 px-4 text-center">
          <p class="text-xs text-gray-500">Keine Notizen vorhanden.</p>
          <UButton variant="link" size="xs" color="primary" @click="isCreateModalOpen = true" class="mt-1">Erstellen</UButton>
        </div>
      </div>
    </div>

    <div class="flex-1 flex flex-col bg-white dark:bg-gray-900 h-full relative min-w-0 w-full overflow-hidden">

      <div v-if="selectedPage" class="flex flex-col h-full w-full">
        <div class="flex items-center justify-between px-4 py-2 border-b border-gray-100 dark:border-gray-800 z-10 shrink-0 bg-white dark:bg-gray-900">
          <div class="flex items-center gap-2 flex-1 min-w-0">
            <UButton icon="i-heroicons-arrow-left" variant="ghost" color="gray" class="md:hidden shrink-0" @click="selectedPage = null" />
            <input
                v-model="selectedPage.title"
                @input="onInputTitle"
                class="bg-transparent font-semibold text-gray-900 dark:text-white focus:outline-none w-full truncate"
                placeholder="Titel..."
            />
          </div>
          <div class="flex items-center gap-2 text-xs text-gray-400 shrink-0 ml-2">
            <span class="hidden sm:inline">{{ isSaving ? 'Speichert...' : 'Gespeichert' }}</span>
            <UButton icon="i-heroicons-trash" color="gray" variant="ghost" size="xs" @click="deleteCurrentPage"/>
          </div>
        </div>

        <div class="flex-1 overflow-hidden relative w-full">
          <div v-if="loadingContent" class="absolute inset-0 flex items-center justify-center bg-white/80 dark:bg-gray-900/80 z-20">
            <UIcon name="i-heroicons-arrow-path" class="w-8 h-8 animate-spin text-primary-500" />
          </div>

          <WikiEditor
              v-model="selectedPage.content"
              class="h-full w-full"
              :page-id="selectedPage.id"
          />
        </div>
      </div>

      <div v-else class="hidden md:flex flex-1 flex-col items-center justify-center w-full h-full bg-gray-50/30 dark:bg-gray-900 p-6 text-center">

        <div class="bg-white dark:bg-gray-800 p-4 rounded-full shadow-sm ring-1 ring-gray-100 dark:ring-gray-700 mb-4">
          <UIcon name="i-heroicons-book-open" class="w-10 h-10 text-primary-200 dark:text-primary-800" />
        </div>

        <h3 class="text-base font-semibold text-gray-900 dark:text-white mb-2">
          Wiki & Dokumentation
        </h3>

        <p class="text-sm text-gray-500 dark:text-gray-400 max-w-xs mx-auto mb-6">
          Wähle links eine Notiz aus oder erstelle einen neuen Eintrag für diesen Datensatz.
        </p>

        <UButton
            icon="i-heroicons-plus"
            color="primary"
            @click="isCreateModalOpen = true"
        >
          Neue Seite erstellen
        </UButton>

      </div>
    </div>

    <UModal v-model:open="isCreateModalOpen">
      <div class="p-5">
        <h3 class="font-bold mb-4">Neue Seite</h3>
        <form @submit.prevent="createPage">
          <UInput v-model="newTitle" placeholder="Titel..." autofocus />
          <div class="mt-4 flex justify-end gap-2">
            <UButton color="gray" variant="ghost" @click="isCreateModalOpen = false">Abbrechen</UButton>
            <UButton type="submit" color="primary" :loading="isCreating">Erstellen</UButton>
          </div>
        </form>
      </div>
    </UModal>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import WikiEditor from '~/components/wiki/WikiEditor.vue'

const props = defineProps<{
  entityType: string
  entityId?: number | null
  entityUuid?: string | null
}>()

const { $api } = useNuxtApp()
const toast = useToast()

const loadingList = ref(false)
const loadingContent = ref(false)
const isCreateModalOpen = ref(false)
const isCreating = ref(false)
const isSaving = ref(false)
const pages = ref<any[]>([])
const selectedPage = ref<any>(null)
const newTitle = ref('')
let saveTimeout: any = null

const getParams = () => {
  const p: any = { entityType: props.entityType }
  if (props.entityId) p.entityId = props.entityId
  else if (props.entityUuid) p.entityUuid = props.entityUuid
  return p
}

async function fetchList() {
  loadingList.value = true
  try {
    const data = await $api('/api/wiki/tree', { method: 'GET', params: getParams() })
    pages.value = data
  } catch (e) {
    console.error("Fetch Error:", e)
  } finally {
    loadingList.value = false
  }
}

async function selectPage(id: string) {
  if (selectedPage.value?.id === id) return
  loadingContent.value = true
  try {
    const data = await $api(`/api/wiki/${id}`, { method: 'GET' })
    selectedPage.value = data
  } catch (e) {
    toast.add({ title: 'Fehler beim Laden', color: 'red' })
  } finally {
    loadingContent.value = false
  }
}

function triggerSave() {
  if (saveTimeout) clearTimeout(saveTimeout)
  isSaving.value = true
  saveTimeout = setTimeout(async () => {
    if (!selectedPage.value) return
    try {
      await $api(`/api/wiki/${selectedPage.value.id}`, {
        method: 'PATCH',
        body: {
          title: selectedPage.value.title,
          content: selectedPage.value.content
        }
      })
      const item = pages.value.find(p => p.id === selectedPage.value.id)
      if (item) item.title = selectedPage.value.title
    } catch (e) {
      console.error(e)
    } finally {
      isSaving.value = false
    }
  }, 1000)
}

function onInputTitle() {
  triggerSave()
}

watch(() => selectedPage.value?.content, (newVal, oldVal) => {
  if (newVal && oldVal && !loadingContent.value) triggerSave()
}, { deep: true })

async function createPage() {
  if (!newTitle.value) return
  isCreating.value = true
  try {
    const res = await $api('/api/wiki', {
      method: 'POST',
      body: { title: newTitle.value, parentId: null, isFolder: false, ...getParams() }
    })
    await fetchList()
    newTitle.value = ''
    isCreateModalOpen.value = false
    await selectPage(res.id)
  } catch (e) {
    console.error(e)
  } finally {
    isCreating.value = false
  }
}

async function deleteCurrentPage() {
  if(!confirm('Löschen?')) return
  await $api(`/api/wiki/${selectedPage.value.id}`, { method: 'DELETE' })
  selectedPage.value = null
  fetchList()
}

onMounted(fetchList)
watch(() => [props.entityId, props.entityUuid], fetchList)
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
.custom-scrollbar::-webkit-scrollbar-thumb { background-color: #ddd; border-radius: 4px; }
</style>
