<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import RelationshipsEditor from '@/components/editor/RelationshipsEditor.vue'
import PageHeader from '@/components/PageHeader.vue'
import DkuSpinner from '@/components/DkuSpinner.vue'
import SearchSelect from '@/components/SearchSelect.vue'
import ConfirmDialog from '@/components/ConfirmDialog.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'

const route = useRoute()
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,
})

// Add modal state
const showAddDialog = ref(false)
const showDeleteAllDialog = ref(false)
const newRelationship = ref({
  firstEntity: '',
  secondEntity: '',
  pseudoSQLExpression: '',
})

// Entity options for SearchSelect
const entityOptions = computed(() => {
  return (store.draftSpec?.entities || []).map(e => ({
    value: e.name,
    label: e.name,
  }))
})

function handleAddRelationship() {
  if (!newRelationship.value.firstEntity || !newRelationship.value.secondEntity) {
    toast.error('Both entities are required')
    return
  }

  if (store.draftSpec) {
    store.draftSpec.relationships.push({
      firstEntity: newRelationship.value.firstEntity,
      secondEntity: newRelationship.value.secondEntity,
      pseudoSQLExpression: newRelationship.value.pseudoSQLExpression.trim(),
    })
    toast.success('Relationship added (click Save to persist)')
    resetAddForm()
  }
}

function resetAddForm() {
  newRelationship.value = { firstEntity: '', secondEntity: '', pseudoSQLExpression: '' }
  showAddDialog.value = false
}

function handleDeleteAll() {
  if (store.draftSpec) {
    store.draftSpec.relationships = []
    toast.success('All relationships deleted')
  }
}
</script>

<template>
  <div class="flex h-full flex-col">
    <PageHeader
      :version-id="versionId"
      title="Relationships"
      description="Define how entities are joined together"
      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">
        <!-- Header row -->
        <div class="mb-4 flex items-center justify-end gap-2">
        <button
          v-if="store.draftSpec.relationships.length > 0"
          class="btn-delete"
          @click="showDeleteAllDialog = true"
        >
          Delete All
        </button>
        <button
          class="btn-tertiary inline-flex items-center gap-1.5"
          @click="showAddDialog = true"
        >
          <i class="dku-icon-plus-16" />
          Add Relationship
        </button>
      </div>

        <RelationshipsEditor
          v-model:relationships="store.draftSpec.relationships"
          :entities="store.draftSpec.entities"
        />
      </div>
    </div>

    <!-- Add Relationship 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 Relationship</h2>
          <p class="mt-1 text-sm text-muted-foreground">
            Define how two entities are joined together
          </p>

          <form class="mt-4 space-y-4" @submit.prevent="handleAddRelationship">
            <div class="flex items-center gap-4">
              <div class="flex-1">
                <label class="mb-1 block text-sm font-medium">First Entity *</label>
                <SearchSelect
                  :model-value="newRelationship.firstEntity"
                  :options="entityOptions"
                  placeholder="Select entity..."
                  search-placeholder="Search entities..."
                  empty-text="No entities found"
                  @update:model-value="(val: string) => newRelationship.firstEntity = val"
                />
              </div>
              <span class="mt-6 text-muted-foreground">↔</span>
              <div class="flex-1">
                <label class="mb-1 block text-sm font-medium">Second Entity *</label>
                <SearchSelect
                  :model-value="newRelationship.secondEntity"
                  :options="entityOptions"
                  placeholder="Select entity..."
                  search-placeholder="Search entities..."
                  empty-text="No entities found"
                  @update:model-value="(val: string) => newRelationship.secondEntity = val"
                />
              </div>
            </div>
            <div>
              <label class="mb-1 block text-sm font-medium">Join Expression</label>
              <input
                v-model="newRelationship.pseudoSQLExpression"
                type="text"
                class="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                placeholder="left.column = right.column"
              />
            </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 All Confirmation Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteAllDialog"
      title="Delete All Relationships"
      :description="`Are you sure you want to delete all ${store.draftSpec?.relationships.length || 0} relationships? Click Save to persist this change.`"
      confirm-text="Delete All"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleDeleteAll"
    />
  </div>
</template>
