<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSemanticModelsStore } from '@/stores/semantic-models'
import { toast } from 'vue-sonner'

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

const isLoading = ref(true)
const errorMessage = ref<string | null>(null)

async function initializeModel() {
  const modelId = route.params.id as string
  isLoading.value = true
  errorMessage.value = null

  try {
    // Load the model to get its versions
    const model = await store.loadModel(modelId)
    if (model.activeVersionId) {
      router.replace(`/semantic-models/${modelId}/v/${model.activeVersionId}/entities`)
      return
    }

    if ((model.versions?.length || 0) === 0) {
      // Auto-create first version when model has none.
      try {
        const newVersion = await store.createVersion(modelId, {}, { refresh: false })
        toast.success(`Created ${newVersion.id}`)
        router.replace(`/semantic-models/${modelId}/v/${newVersion.id}/entities`)
      } catch (e) {
        isLoading.value = false
        errorMessage.value = e instanceof Error ? e.message : 'Failed to create initial version'
      }
      return
    }

    isLoading.value = false
    errorMessage.value = 'Model has versions but no active version is set'
  } catch (e) {
    isLoading.value = false
    errorMessage.value = e instanceof Error ? e.message : 'Failed to load model'
  }
}

onMounted(initializeModel)
</script>

<template>
  <div class="flex justify-center items-center h-full">
    <!-- Loading state -->
    <div v-if="isLoading" class="flex flex-col items-center gap-4">
      <div
        class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"
      ></div>
      <span class="text-muted-foreground">Loading model...</span>
    </div>

    <!-- Error state -->
    <div v-else-if="errorMessage" class="flex flex-col items-center gap-4 max-w-md text-center">
      <i class="dku-icon-error-circle-outline-48 text-destructive" />
      <div>
        <h2 class="text-lg font-semibold mb-2">Failed to Initialize Model</h2>
        <p class="text-muted-foreground text-sm mb-4">{{ errorMessage }}</p>
      </div>
      <button
        @click="initializeModel"
        class="inline-flex items-center gap-2 px-4 py-2 rounded-md bg-primary text-primary-foreground hover:bg-primary/90"
      >
        <i class="dku-icon-arrow-clockwise-16" />
        Retry
      </button>
    </div>
  </div>
</template>
