<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSemanticModelsStore } from '@/stores/semantic-models'
import VersionSelectorModal from '@/components/VersionSelectorModal.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { useRouteVersionId } from '@/composables/useRouteVersionId'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { formatDateTime } from '@/lib/utils'

const route = useRoute()
const router = useRouter()
const store = useSemanticModelsStore()

// Modal state
const showVersionSelector = ref(false)
const showUnsavedDialog = ref(false)

// Entity list expansion
const entitiesExpanded = ref(true)

// Route-derived state
const currentModelId = computed(() => route.params.id as string | undefined)
const currentVersionId = useRouteVersionId(route)
const currentEntityId = computed(() => route.params.entityId as string | undefined)
const hasModelContext = computed(() => !!currentModelId.value && !!currentVersionId.value)
const isActiveCurrent = computed(() => {
  if (!currentVersionId.value) return false
  return store.isActiveVersion(currentVersionId.value)
})

// Load model when route changes
watch(
  currentModelId,
  async (modelId) => {
    if (modelId) {
      await store.loadModel(modelId)
    }
  },
  { immediate: true }
)

// Load version when route changes
watch(
  [currentModelId, currentVersionId],
  async ([modelId, version]) => {
    if (modelId && version) {
      await store.loadVersion(modelId, version)
    }
  },
  { immediate: true }
)

// Entities from current version
const entities = computed(
  () => store.draftSpec?.entities || store.currentVersion?.entities || []
)

const lastIndexedAtLabel = computed(() => {
  const raw = store.currentVersion?.privateEditorData?.lastIndexedAt
  if (typeof raw !== 'string' || !raw) return 'Never'
  const formatted = formatDateTime(raw)
  return formatted || 'Never'
})

// Counts for sidebar badges
const relationshipsCount = computed(
  () => store.draftSpec?.relationships?.length || 0
)

const glossaryTermsCount = computed(
  () => store.draftGlossaryTerms?.length || 0
)

const goldenQueriesCount = computed(
  () => store.draftGoldenQueries?.length || 0
)

// Navigation helpers
function isEntityActive(entityId: string): boolean {
  return currentEntityId.value === entityId
}

function isRelationshipsActive(): boolean {
  return route.name === 'relationships-editor'
}

function isInstructionsActive(): boolean {
  return route.name === 'instructions-editor'
}

function isGlossaryActive(): boolean {
  return route.name === 'glossary-editor'
}

function isGoldenQueriesActive(): boolean {
  return route.name === 'golden-queries-editor'
}

function isPlaygroundActive(): boolean {
  return route.name === 'version-playground' || route.path === '/playground'
}

function isIndexingActive(): boolean {
  return route.name === 'indexing'
}

// Navigation actions
function navigateToEntity(entityId: string) {
  if (currentModelId.value && currentVersionId.value) {
    router.push(
      `/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/entities/${encodeURIComponent(entityId)}`
    )
  }
}

function navigateToEntities() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(`/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/entities`)
  }
}

function navigateToRelationships() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(
      `/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/relationships`
    )
  }
}

function navigateToInstructions() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(
      `/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/instructions`
    )
  }
}

function navigateToGlossary() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(`/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/glossary`)
  }
}

function navigateToGoldenQueries() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(`/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/golden-queries`)
  }
}

function navigateToIndexing() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(`/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/indexing`)
  }
}

function navigateToPlayground() {
  if (currentModelId.value && currentVersionId.value) {
    router.push(
      `/semantic-models/${currentModelId.value}/v/${currentVersionId.value}/playground`
    )
  } else {
    router.push('/playground')
  }
}

function openVersionSelector() {
  if (store.hasUnsavedChanges) {
    showUnsavedDialog.value = true
    return
  }
  showVersionSelector.value = true
}

function handleConfirmDiscard() {
  store.discardDraft()
  showUnsavedDialog.value = false
  showVersionSelector.value = true
}

// Modal handlers
function handleVersionSelect(versionId: string) {
  if (currentModelId.value) {
    // Preserve the current section (entities, relationships, etc.) when switching versions
    const currentPath = route.path
    const versionPattern = /\/v\/[^/]+/
    if (versionPattern.test(currentPath)) {
      // Replace the version in the current path
      const newPath = currentPath.replace(versionPattern, `/v/${versionId}`)
      router.push(newPath)
    } else {
      // Fallback: navigate to version root (will redirect to entities)
      router.push(`/semantic-models/${currentModelId.value}/v/${versionId}`)
    }
  }
}

function handleVersionCreate() {
  // Will be handled by the modal's create event -> navigates after creation
}
</script>

<template>
  <aside
    class="flex h-full w-64 flex-col border-r border-sidebar-border bg-sidebar-background text-sidebar-foreground"
  >
    <!-- Version selector header (aligned with PageHeader) -->
    <div v-if="hasModelContext" class="border-b border-sidebar-border px-3 py-2">
      <button
        class="tile-title-222 flex w-full items-center justify-between rounded-md bg-sidebar-accent/50 px-3 py-2 transition-colors hover:bg-sidebar-accent"
        @click="openVersionSelector"
      >
        <span class="flex items-center gap-2">
          {{ currentVersionId }}
          <span
            v-if="isActiveCurrent"
            class="rounded-full bg-primary/10 px-1.5 py-0.5 text-xs text-primary"
          >
            Active
          </span>
        </span>
        <i class="dku-icon-chevron-down-16 text-muted-foreground" />
      </button>
    </div>

    <!-- Navigation -->
    <nav class="flex-1 overflow-y-auto p-3">
      <!-- Model-context navigation (only when model is selected) -->
      <template v-if="hasModelContext">
        <!-- Version-scoped navigation -->
        <div class="space-y-0.5">
            <!-- Entities (expandable) -->
            <div>
              <button
                class="body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors hover:bg-sidebar-accent"
                @click="navigateToEntities"
              >
                <span class="flex items-center gap-2">
                  <i class="dku-icon-cube-20 text-muted-foreground"></i>
                  Entities
                  <span class="rounded-full bg-sidebar-accent px-1.5 py-0.5 text-xs">
                    {{ entities.length }}
                  </span>
                </span>
                <span class="flex items-center gap-2">
                  <span
                    v-if="store.isEntitiesDirty"
                    class="h-2 w-2 rounded-full bg-amber-500"
                    title="Unsaved changes"
                  ></span>
                  <span
                    class="rounded p-1 hover:bg-sidebar-accent"
                    @click.stop="entitiesExpanded = !entitiesExpanded"
                  >
                    <i
                      :class="entitiesExpanded ? 'dku-icon-chevron-down-12' : 'dku-icon-chevron-right-12'"
                      class="text-muted-foreground"
                    />
                  </span>
                </span>
              </button>

              <!-- Entity list -->
              <div v-if="entitiesExpanded" class="ml-5 mt-0.5 space-y-0.5">
                <button
                  v-for="entity in entities"
                  :key="entity.name"
                  :class="[
                    isEntityActive(entity.name)
                      ? 'bg-sidebar-accent'
                      : 'hover:bg-sidebar-accent',
                    'body-444 flex w-full items-center gap-2 rounded-md px-2 py-1 transition-colors',
                  ]"
                  @click="navigateToEntity(entity.name)"
                >
                  <span class="truncate">{{ entity.name }}</span>
                </button>

                <p
                  v-if="entities.length === 0"
                  class="px-2 py-1 text-xs text-muted-foreground"
                >
                  No entities yet
                </p>
              </div>
            </div>

            <!-- Relationships -->
            <button
              :class="[
                isRelationshipsActive()
                  ? 'bg-sidebar-accent'
                  : 'hover:bg-sidebar-accent',
                'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
              ]"
              @click="navigateToRelationships"
            >
              <span class="flex items-center gap-2">
                <i class="dku-icon-link-16 text-muted-foreground" />
                Relationships
                <span class="rounded-full bg-sidebar-accent px-1.5 py-0.5 text-xs">
                  {{ relationshipsCount }}
                </span>
              </span>
              <span
                v-if="store.isRelationshipsDirty"
                class="h-2 w-2 rounded-full bg-amber-500"
                title="Unsaved changes"
              ></span>
            </button>

          
            <!-- Glossary -->
            <button
              :class="[
                isGlossaryActive()
                  ? 'bg-sidebar-accent'
                  : 'hover:bg-sidebar-accent',
                'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
              ]"
              @click="navigateToGlossary"
            >
              <span class="flex items-center gap-2">
                <i class="dku-icon-book-16 text-muted-foreground" />
                Glossary
                <span class="rounded-full bg-sidebar-accent px-1.5 py-0.5 text-xs">
                  {{ glossaryTermsCount }}
                </span>
              </span>
              <span
                v-if="store.isGlossaryDirty"
                class="h-2 w-2 rounded-full bg-amber-500"
                title="Unsaved changes"
              ></span>
            </button>

            <!-- Golden Queries -->
            <button
              :class="[
                isGoldenQueriesActive()
                  ? 'bg-sidebar-accent'
                  : 'hover:bg-sidebar-accent',
                'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
              ]"
              @click="navigateToGoldenQueries"
            >
              <span class="flex items-center gap-2">
                <i class="dku-icon-sql-16 text-muted-foreground"></i>
                Golden Queries
                <span class="rounded-full bg-sidebar-accent px-1.5 py-0.5 text-xs">
                  {{ goldenQueriesCount }}
                </span>
              </span>
              <span
                v-if="store.isGoldenQueriesDirty"
                class="h-2 w-2 rounded-full bg-amber-500"
                title="Unsaved changes"
              ></span>
            </button>

              <!-- Instructions -->
            <button
              :class="[
                isInstructionsActive()
                  ? 'bg-sidebar-accent'
                  : 'hover:bg-sidebar-accent',
                'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
              ]"
              @click="navigateToInstructions"
            >
              <span class="flex items-center gap-2">
                <i class="dku-icon-file-text-16 text-muted-foreground" />
                Instructions
              </span>
              <span
                v-if="store.isInstructionsDirty"
                class="h-2 w-2 rounded-full bg-amber-500"
                title="Unsaved changes"
              ></span>
            </button>
          </div>

        <!-- Separator -->
        <div class="my-2 border-t border-sidebar-border"></div>

        <!-- Indexing -->
        <button
          :class="[
            isIndexingActive()
              ? 'bg-sidebar-accent'
              : 'hover:bg-sidebar-accent',
            'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
          ]"
          @click="navigateToIndexing"
        >
          <span class="flex items-center gap-2">
            <i class="dku-icon-database-sql-16 text-muted-foreground" />
            Indexing
          </span>
          <span class="flex items-center gap-2">
            <Tooltip v-if="store.isIndexingStale">
              <TooltipTrigger as-child>
                <span class="inline-flex items-center">
                  <i class="dku-icon-warning-outline-16 text-amber-500" />
                </span>
              </TooltipTrigger>
              <TooltipContent>
                <div class="space-y-0.5">
                  <div>Indexing required</div>
                  <div class="text-xs text-muted-foreground">
                    Last indexed: {{ lastIndexedAtLabel }}
                  </div>
                </div>
              </TooltipContent>
            </Tooltip>
            <span
              v-if="store.isIndexingDirty"
              class="h-2 w-2 rounded-full bg-amber-500"
              title="Unsaved changes"
            ></span>
          </span>
        </button>

        <div class="my-2 border-t border-sidebar-border"></div>

        <!-- Playground (outside version scope) -->
        <button
          :class="[
            isPlaygroundActive()
              ? 'bg-sidebar-accent'
              : 'hover:bg-sidebar-accent',
            'body-333 flex w-full items-center justify-between rounded-md px-2 py-1.5 transition-colors',
          ]"
          @click="navigateToPlayground"
        >
          <span class="flex items-center gap-2">
            <i class="dku-icon-beaker-16" />
            Playground
          </span>
          <span
            v-if="store.isPlaygroundDirty"
            class="h-2 w-2 rounded-full bg-amber-500"
            title="Unsaved changes"
          ></span>
        </button>
      </template>

    </nav>

    <!-- Modals -->
    <VersionSelectorModal
      v-if="currentModelId && currentVersionId"
      v-model:open="showVersionSelector"
      :model-id="currentModelId"
      :current-version-id="currentVersionId"
      @select="handleVersionSelect"
      @create="handleVersionCreate"
    />

    <ConfirmDialog
      v-model:open="showUnsavedDialog"
      title="Unsaved changes"
      description="You have unsaved changes. Discard them and choose another version?"
      confirm-text="Discard changes"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDiscard"
    />
  </aside>
</template>
