<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute, useRouter } 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'
import { toast } from 'vue-sonner'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import type { GoldenQuery } from '@/types'

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

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

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

const { handleSave, handleDiscard } = useSaveDiscard({
  modelId,
  versionId,
})

// UI State
const showAddDialog = ref(false)
const showDeleteDialog = ref(false)
const queryToDelete = ref<GoldenQuery | null>(null)

// Add form
const newQuery = ref({
  name: '',
  question: '',
  generatedSql: '',
})

// Use draftGoldenQueries from store
const goldenQueries = computed(() => store.draftGoldenQueries)

function handleCreate() {
  if (!newQuery.value.name.trim() || !newQuery.value.question.trim()) {
    toast.error('Name and question are required')
    return
  }

  // Add to draft (not saved until user clicks Save)
  const gq: GoldenQuery = {
    name: newQuery.value.name.trim(),
    question: newQuery.value.question.trim(),
    generatedSql: newQuery.value.generatedSql.trim(),
    created: { on: new Date().toISOString() },
  }
  store.draftGoldenQueries.push(gq)
  toast.success('Golden query added (click Save to persist)')
  resetAddForm()
}

function resetAddForm() {
  newQuery.value = { name: '', question: '', generatedSql: '' }
  showAddDialog.value = false
}

function openDeleteDialog(query: GoldenQuery) {
  queryToDelete.value = query
  showDeleteDialog.value = true
}

function handleDelete() {
  if (!queryToDelete.value) return

  // Remove from draft (not saved until user clicks Save)
  const index = store.draftGoldenQueries.findIndex(gq => gq === queryToDelete.value)
  if (index !== -1) {
    store.draftGoldenQueries.splice(index, 1)
    toast.success('Golden query removed (click Save to persist)')
  }
  queryToDelete.value = null
}

function useInPlayground(query: GoldenQuery) {
  router.push({
    path: `/semantic-models/${modelId.value}/v/${versionId.value}/playground`,
    query: {
      question: query.question,
    },
  })
}

</script>

<template>
  <div class="flex h-full flex-col">
    <PageHeader
      :version-id="versionId"
      title="Golden Queries"
      description="Saved queries for testing and validation"
      show-save-discard
      :has-unsaved-changes="store.hasUnsavedChanges"
      :is-saving="store.isSavingDraft"
      @save="handleSave"
      @discard="handleDiscard"
    />

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

    <!-- Content -->
    <div v-else class="flex-1 overflow-auto p-6">
      <div class="mx-auto max-w-6xl">
        <!-- Header row -->
        <div class="mb-4 flex items-center justify-end">
          <button
            class="btn-tertiary inline-flex items-center gap-1.5"
            @click="showAddDialog = true"
          >
            <i class="dku-icon-plus-16" />
            Add Query
          </button>
        </div>

        <!-- Empty state -->
        <div
          v-if="goldenQueries.length === 0"
          class="rounded-lg border-2 border-dashed p-12 text-center"
        >
          <i class="dku-icon-sql-32 mx-auto text-muted-foreground"></i>
          <h3 class="mt-4 font-semibold">No golden queries yet</h3>
          <p class="mt-2 text-sm text-muted-foreground">
            Golden queries are saved SQL queries that serve as test cases for your semantic model.
            Create them manually or save successful queries from the Playground.
          </p>
        </div>

        <!-- Queries list -->
        <div v-else class="space-y-4">
          <div
            v-for="query in goldenQueries"
            :key="`${query.name}:${query.question}`"
            class="rounded-lg border bg-card p-4"
          >
            <div class="flex items-start justify-between">
              <div class="flex-1">
                <h3 class="font-medium">{{ query.name }}</h3>
                <p class="mt-1 text-sm text-muted-foreground">{{ query.question }}</p>
                <pre
                  v-if="query.generatedSql"
                  class="mt-3 overflow-x-auto rounded bg-muted p-3 text-xs"
                >{{ query.generatedSql }}</pre>
                <div class="mt-2 flex items-center gap-4 text-xs text-muted-foreground">
                  <span v-if="query.created?.by">By {{ query.created.by }}</span>
                </div>
              </div>

              <div class="ml-4 flex items-center gap-1">
                <Tooltip>
                  <TooltipTrigger as-child>
                    <button
                      class="inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
                      @click="useInPlayground(query)"
                    >
                      <i class="dku-icon-play-outline-16"></i>
                    </button>
                  </TooltipTrigger>
                  <TooltipContent>Use in Playground</TooltipContent>
                </Tooltip>
                <Tooltip>
                  <TooltipTrigger as-child>
                    <button
                      class="inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 text-sm font-medium text-destructive hover:bg-destructive/10"
                      @click="openDeleteDialog(query)"
                    >
                      <i class="dku-icon-trash-16" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent>Delete</TooltipContent>
                </Tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Dialog -->
    <Teleport to="body">
      <div
        v-if="showAddDialog"
        class="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      >
        <div class="w-full max-w-lg rounded-lg bg-background p-6 shadow-lg">
          <h2 class="text-lg font-semibold">Add Golden Query</h2>
          <p class="mt-1 text-sm text-muted-foreground">
            Create a test query for your semantic model
          </p>

          <form class="mt-4 space-y-4" @submit.prevent="handleCreate">
            <div>
              <label class="mb-1 block text-sm font-medium">Name *</label>
              <input
                v-model="newQuery.name"
                type="text"
                class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                placeholder="Golden query name"
                required
              />
            </div>
            <div>
              <label class="mb-1 block text-sm font-medium">Question *</label>
              <textarea
                v-model="newQuery.question"
                class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                placeholder="Natural language question"
                rows="2"
                required
              />
            </div>
            <div>
              <label class="mb-1 block text-sm font-medium">Expected SQL</label>
              <textarea
                v-model="newQuery.generatedSql"
                class="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                placeholder="Expected SQL query"
                rows="4"
              />
            </div>
            <div class="flex justify-end gap-2">
              <button
                type="button"
                class="btn-secondary"
                @click="resetAddForm"
              >
                Cancel
              </button>
              <button
                type="submit"
                class="btn-primary"
              >
                Add
              </button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>

    <!-- Delete Confirmation -->
    <ConfirmDialog
      v-model:open="showDeleteDialog"
      title="Delete Golden Query"
      :description="`Are you sure you want to delete '${queryToDelete?.name}'? Click Save to persist this change.`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleDelete"
    />
  </div>
</template>
