<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import PageHeader from '@/components/PageHeader.vue'
import DkuSpinner from '@/components/DkuSpinner.vue'
import { useRouteVersionId } from '@/composables/useRouteVersionId'
import { useVersionLoader } from '@/composables/useVersionLoader'
import { useSaveDiscard } from '@/composables/useSaveDiscard'
import { useSemanticModelsStore } from '@/stores/semantic-models'

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

const modelId = computed(() => route.params.id as string)
const versionId = useRouteVersionId(route)

const modelInstructions = computed({
  get: () => {
    const raw = (store.draftSqlGenerationConfig || {}) as Record<string, unknown>
    const value = raw.instructions
    return typeof value === 'string' ? value : ''
  },
  set: (value: string) => {
    const next = { ...(store.draftSqlGenerationConfig || {}) } as Record<string, unknown>
    if (value) {
      next.instructions = value
    } else {
      delete next.instructions
    }
    store.draftSqlGenerationConfig = next
  },
})

const { isLoading } = useVersionLoader({
  modelId,
  versionId,
})

const { handleSave, handleDiscard } = useSaveDiscard({
  modelId,
  versionId,
})
</script>

<template>
  <div class="flex h-full flex-col">
    <PageHeader
      :version-id="versionId"
      title="Instructions"
      description="These instructions will be included in every SQL generation query to help guide the AI."
      show-save-discard
      :has-unsaved-changes="store.hasUnsavedChanges"
      :is-saving="store.isSavingDraft"
      @save="handleSave"
      @discard="handleDiscard"
    />

    <!-- Loading state -->
    <div v-if="isLoading" class="flex flex-1 items-center justify-center">
      <DkuSpinner size="xl" />
    </div>

    <!-- Content -->
    <div v-else-if="store.draftSpec" class="flex-1 overflow-auto p-6">
      <div class="mx-auto max-w-6xl">
        <div class="bg-card p-6">
          <textarea
            v-model="modelInstructions"
            class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[200px] resize-y"
            placeholder="Instructions ..."
          />
        </div>
      </div>
    </div>
  </div>
</template>
