<script setup lang="ts">
import { computed, ref } from 'vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import SearchSelect from '@/components/SearchSelect.vue'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import type { Relationship, EntityClass } from '@/types'

// Props
const props = defineProps<{
  relationships: Relationship[]
  entities: EntityClass[]
}>()

// Emits
const emit = defineEmits<{
  'update:relationships': [relationships: Relationship[]]
}>()

// Computed for v-model binding
const localRelationships = computed({
  get: () => props.relationships,
  set: (val) => emit('update:relationships', val),
})

// Entity options for SearchSelect
const entityOptions = computed(() => {
  return props.entities.map(e => ({
    value: e.name,
    label: e.name,
  }))
})

// Delete confirmation dialog state
const showDeleteDialog = ref(false)
const relationshipToDelete = ref<{ index: number; description: string } | null>(null)

function getEntityName(entityId: string): string {
  const entity = props.entities.find(e => e.name === entityId)
  return entity?.name || entityId || '?'
}

function openDeleteDialog(index: number) {
  const rel = localRelationships.value[index]
  const leftName = getEntityName(rel.firstEntity)
  const rightName = getEntityName(rel.secondEntity)
  relationshipToDelete.value = { index, description: `${leftName} ↔ ${rightName}` }
  showDeleteDialog.value = true
}

function handleConfirmDelete() {
  if (relationshipToDelete.value !== null) {
    localRelationships.value.splice(relationshipToDelete.value.index, 1)
  }
  relationshipToDelete.value = null
}
</script>

<template>
  <div>
    <div v-if="relationships.length === 0" class="p-8 text-center text-muted-foreground">
      No relationships defined.
    </div>

    <div v-else class="divide-y">
      <div
        v-for="(_rel, relIndex) in relationships"
        :key="relIndex"
        class="flex items-center gap-4 p-4"
      >
        <div class="w-40">
          <SearchSelect
            :model-value="localRelationships[relIndex].firstEntity"
            :options="entityOptions"
            placeholder="Select entity..."
            search-placeholder="Search entities..."
            empty-text="No entities found"
            @update:model-value="(val: string) => localRelationships[relIndex].firstEntity = val"
          />
        </div>
        <span class="text-muted-foreground">↔</span>
        <div class="w-40">
          <SearchSelect
            :model-value="localRelationships[relIndex].secondEntity"
            :options="entityOptions"
            placeholder="Select entity..."
            search-placeholder="Search entities..."
            empty-text="No entities found"
            @update:model-value="(val: string) => localRelationships[relIndex].secondEntity = val"
          />
        </div>
        <input
          v-model="localRelationships[relIndex].pseudoSQLExpression"
          type="text"
          class="flex-1 rounded-md border border-input bg-background px-3 py-2 text-sm font-mono"
          placeholder="left.column = right.column"
        />
        <Tooltip>
          <TooltipTrigger as-child>
            <button
              class="rounded p-1 text-destructive hover:bg-destructive/10"
              @click="openDeleteDialog(relIndex)"
            >
              <i class="dku-icon-trash-16" />
            </button>
          </TooltipTrigger>
          <TooltipContent>Delete</TooltipContent>
        </Tooltip>
      </div>
    </div>

    <!-- Delete Relationship Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteDialog"
      title="Delete Relationship"
      :description="`Are you sure you want to delete the relationship '${relationshipToDelete?.description}'?`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDelete"
    />
  </div>
</template>
