<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import MultiSelect from '@/components/MultiSelect.vue'
import SearchSelect from '@/components/SearchSelect.vue'
import DkuSpinner from '@/components/DkuSpinner.vue'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import type { Attribute, EntityClass, DSSColumn, DSSProject, DSSDataset } from '@/types'

// Props
const props = defineProps<{
  entity: EntityClass
  entityIndex: number
  columns: DSSColumn[]
  loadingColumns: boolean
  // DSS Resources
  projects: DSSProject[]
  datasets: Record<string, DSSDataset[]>
  // Loading states
  loadingProjects: boolean
  loadingDatasets: Record<string, boolean>
}>()

// Emits
const emit = defineEmits<{
  'update:entity': [entity: EntityClass]
  'name-change': [newName: string]
  'project-change': [projectKey: string]
  'dataset-change': []
  'open-values-modal': [attrIndex: number]
  'delete': []
}>()

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

function splitDatasetRef(ref: string | undefined): { projectKey: string; datasetName: string } {
  if (!ref || !ref.includes('.')) {
    return { projectKey: '', datasetName: '' }
  }
  const [projectKey, datasetName] = ref.split('.', 2)
  return { projectKey, datasetName }
}

const datasetProject = ref('')
const datasetName = ref('')

function updateDatasetRef() {
  localEntity.value.type = 'DATASET'
  if (datasetProject.value && datasetName.value) {
    localEntity.value.datasetRef = `${datasetProject.value}.${datasetName.value}`
  } else {
    localEntity.value.datasetRef = undefined
  }
}

watch(
  () => props.entity.datasetRef,
  (newRef) => {
    const { projectKey, datasetName: ds } = splitDatasetRef(newRef)
    datasetProject.value = projectKey
    datasetName.value = ds
    if (newRef) {
      localEntity.value.type = 'DATASET'
    }
  },
  { immediate: true }
)

// Name editing state
const isEditingName = ref(false)
const nameInputRef = ref<HTMLInputElement | null>(null)
const editingName = ref('')

function startEditingName() {
  editingName.value = localEntity.value.name
  isEditingName.value = true
  setTimeout(() => nameInputRef.value?.focus(), 0)
}

function saveEditingName() {
  localEntity.value.name = editingName.value
  isEditingName.value = false
  emit('name-change', editingName.value)
}

function cancelEditingName() {
  isEditingName.value = false
}

// Delete confirmation dialog state
const showDeleteAttributeDialog = ref(false)
const showDeleteMetricDialog = ref(false)
const showDeleteFilterDialog = ref(false)
const itemToDelete = ref<{ index: number; name: string; type: 'attribute' | 'metric' | 'filter' } | null>(null)

// Section collapse state (all expanded by default)
const sectionsExpanded = ref<Record<'attributes' | 'metrics' | 'filters', boolean>>({
  attributes: true,
  metrics: true,
  filters: true,
})

function toggleSection(section: 'attributes' | 'metrics' | 'filters') {
  sectionsExpanded.value[section] = !sectionsExpanded.value[section]
}

// Attribute filters
const attributeFilters = ref({
  name: '',
  source: '',
  type: '',
  description: '',
})

const filteredAttributes = computed(() => {
  return props.entity.attributes.filter((attr) => {
    const nameMatch = !attributeFilters.value.name ||
      (attr.name || '').toLowerCase().includes(attributeFilters.value.name.toLowerCase())
    const sourceMatch = !attributeFilters.value.source ||
      (attr.column || '').toLowerCase().includes(attributeFilters.value.source.toLowerCase()) ||
      (attr.pseudoSQLExpression || '').toLowerCase().includes(attributeFilters.value.source.toLowerCase())
    const typeMatch = !attributeFilters.value.type ||
      (attr.dssType || '').toLowerCase().includes(attributeFilters.value.type.toLowerCase())
    const descMatch = !attributeFilters.value.description ||
      (attr.description || '').toLowerCase().includes(attributeFilters.value.description.toLowerCase())
    return nameMatch && sourceMatch && typeMatch && descMatch
  }).map((attr) => ({
    attr,
    originalIndex: props.entity.attributes.indexOf(attr),
  }))
})

// Attribute CRUD
function addAttribute() {
  localEntity.value.attributes.unshift({
    name: '',
    type: 'COLUMN',
    dssType: '',
    column: '',
    pseudoSQLExpression: undefined,
    distinctValuesHandlingMode: 'NONE',
    manualValues: [],
    indexDistinctValues: false,
    resolveInUserRequests: false,
  })
}

function openDeleteAttributeDialog(attrIndex: number) {
  const attr = localEntity.value.attributes[attrIndex]
  itemToDelete.value = { index: attrIndex, name: attr.name, type: 'attribute' }
  showDeleteAttributeDialog.value = true
}

function handleConfirmDeleteAttribute() {
  if (itemToDelete.value?.type === 'attribute') {
    localEntity.value.attributes.splice(itemToDelete.value.index, 1)
  }
  itemToDelete.value = null
}

// Metric CRUD
function addMetric() {
  localEntity.value.metrics.unshift({
    name: 'new_metric',
    pseudoSQLExpression: '',
  })
}

function openDeleteMetricDialog(metricIndex: number) {
  const metric = localEntity.value.metrics[metricIndex]
  itemToDelete.value = { index: metricIndex, name: metric.name, type: 'metric' }
  showDeleteMetricDialog.value = true
}

function handleConfirmDeleteMetric() {
  if (itemToDelete.value?.type === 'metric') {
    localEntity.value.metrics.splice(itemToDelete.value.index, 1)
  }
  itemToDelete.value = null
}

// Filter CRUD
function addFilter() {
  localEntity.value.filters.unshift({
    name: 'new_filter',
    pseudoSQLExpression: '',
  })
}

function openDeleteFilterDialog(filterIndex: number) {
  const filter = localEntity.value.filters[filterIndex]
  itemToDelete.value = { index: filterIndex, name: filter.name, type: 'filter' }
  showDeleteFilterDialog.value = true
}

function handleConfirmDeleteFilter() {
  if (itemToDelete.value?.type === 'filter') {
    localEntity.value.filters.splice(itemToDelete.value.index, 1)
  }
  itemToDelete.value = null
}

// Column selection handler
function handleColumnSelect(attrIndex: number, columnName: string) {
  const attr = localEntity.value.attributes[attrIndex]
  if (!attr) return

  attr.column = columnName

  const col = props.columns.find(c => c.name === columnName)
  if (col) {
    if (!(attr.name || '').trim()) {
      attr.name = col.name
    }
    if (!(attr.description || '').trim() && col.comment?.trim()) {
      attr.description = col.comment.trim()
    }
    attr.dssType = col.type
  } else if (!(attr.name || '').trim() && columnName) {
    attr.name = columnName
  }
}

// Check if attribute is a simple column (not computed)
function isSimpleColumn(attr: { type?: string; column?: string; pseudoSQLExpression?: string; name?: string }): boolean {
  return getAttributeMode(attr) === 'COLUMN'
}

type SourceMode = 'COLUMN' | 'EXPRESSION'

function getAttributeMode(attr: { type?: string; pseudoSQLExpression?: string; name?: string }): SourceMode {
  if (attr.type === 'EXPRESSION') {
    return 'EXPRESSION'
  }
  if (attr.type === 'COLUMN') {
    return 'COLUMN'
  }
  const expression = (attr.pseudoSQLExpression || '').trim()
  if (expression && expression !== (attr.name || '').trim()) {
    return 'EXPRESSION'
  }
  return 'COLUMN'
}

function setAttributeMode(attr: Attribute, mode: SourceMode) {
  attr.type = mode
  if (mode === 'EXPRESSION') {
    attr.resolveInUserRequests = false
  }
  syncDistinctValues(attr)
}

function isAttributeNameMissing(attr: Attribute): boolean {
  return !((attr.name || '').trim())
}

function isAttributeColumnMissing(attr: Attribute): boolean {
  return getAttributeMode(attr) === 'COLUMN' && !((attr.column || '').trim())
}

function isAttributeExpressionMissing(attr: Attribute): boolean {
  return getAttributeMode(attr) === 'EXPRESSION' && !((attr.pseudoSQLExpression || '').trim())
}

function syncDistinctValues(attr: { manualValues?: string[]; resolveInUserRequests?: boolean; distinctValuesHandlingMode?: string; indexDistinctValues?: boolean }) {
  const hasManual = (attr.manualValues || []).length > 0
  if (hasManual || attr.distinctValuesHandlingMode === 'MANUAL') {
    attr.distinctValuesHandlingMode = 'MANUAL'
    attr.indexDistinctValues = false
    return
  }
  if (attr.distinctValuesHandlingMode === 'AUTO_INDEX') {
    attr.indexDistinctValues = true
    return
  }
  if (attr.resolveInUserRequests) {
    attr.distinctValuesHandlingMode = 'AUTO_INDEX'
    attr.indexDistinctValues = true
    return
  }
  if (attr.indexDistinctValues) {
    attr.distinctValuesHandlingMode = 'AUTO_INDEX'
    return
  }
  attr.distinctValuesHandlingMode = 'NONE'
  attr.indexDistinctValues = false
}

function setAttributeExpression(attr: Attribute, value: string) {
  attr.pseudoSQLExpression = value
}

// Column options derived from source columns
const columnOptions = computed(() => {
  return props.columns.map(col => ({
    value: col.name,
    label: col.name,
  }))
})

// Attribute options for selectors that must use semantic attribute names
const attributeNameOptions = computed(() => {
  const seen = new Set<string>()
  return localEntity.value.attributes.reduce<Array<{ value: string; label: string }>>((acc, attr) => {
    const name = (attr.name || '').trim()
    if (!name || seen.has(name)) {
      return acc
    }
    seen.add(name)
    acc.push({ value: name, label: name })
    return acc
  }, [])
})

watch(
  attributeNameOptions,
  (options) => {
    const validNames = new Set(options.map(option => option.value))
    const current = localEntity.value.primaryKey?.attributes || []
    const sanitized = current.filter(name => validNames.has(name))
    if (sanitized.length !== current.length) {
      localEntity.value.primaryKey = { attributes: sanitized }
    }
  },
  { immediate: true }
)

// Project options
const projectOptions = computed(() => {
  return props.projects.map(proj => ({
    value: proj.key,
    label: `${proj.name} (${proj.key})`,
  }))
})

// Dataset options
const datasetOptions = computed(() => {
  const projDatasets = props.datasets[datasetProject.value || ''] || []
  return projDatasets.map(ds => ({
    value: ds.name,
    label: `${ds.name} (${ds.type})`,
  }))
})

// Primary key v-model
const primaryKeyValue = computed({
  get: () => localEntity.value.primaryKey?.attributes || [],
  set: (val) => {
    localEntity.value.primaryKey = { attributes: val }
  },
})

</script>

<template>
  <div class="p-4">
    <!-- Entity Details -->
    <div class="space-y-4">
      <!-- Entity name (inline editable) -->
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-2">
          <div v-if="isEditingName" class="flex items-center gap-1">
            <input
              ref="nameInputRef"
              v-model="editingName"
              type="text"
              class="h-8 w-64 rounded border border-input bg-background px-2 text-sm focus:outline-none"
              placeholder="Entity name"
              @keydown.enter="saveEditingName"
              @keydown.escape="cancelEditingName"
            />
            <Tooltip>
              <TooltipTrigger as-child>
                <button
                  class="rounded p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-900/30"
                  @click="saveEditingName"
                >
                  <i class="dku-icon-checkmark-12" />
                </button>
              </TooltipTrigger>
              <TooltipContent>Save</TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger as-child>
                <button
                  class="rounded p-1.5 text-muted-foreground hover:bg-muted"
                  @click="cancelEditingName"
                >
                  <i class="dku-icon-dismiss-12" />
                </button>
              </TooltipTrigger>
              <TooltipContent>Cancel</TooltipContent>
            </Tooltip>
          </div>
          <template v-else>
            <h1 class="text-xl font-semibold">{{ localEntity.name || 'Untitled Entity' }}</h1>
            <Tooltip>
              <TooltipTrigger as-child>
                <button
                  class="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
                  @click="startEditingName"
                >
                  <i class="dku-icon-edit-16" />
                </button>
              </TooltipTrigger>
              <TooltipContent>Edit name</TooltipContent>
            </Tooltip>
          </template>
        </div>
        <Tooltip>
          <TooltipTrigger as-child>
            <button
              class="btn-delete"
              @click="emit('delete')"
            >
              Delete
            </button>
          </TooltipTrigger>
          <TooltipContent>Delete this entity</TooltipContent>
        </Tooltip>
      </div>

      <!-- Entity description -->
      <div>
        <label class="mb-1 block text-sm font-medium">Description</label>
        <textarea
          v-model="localEntity.description"
          class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
          placeholder="Describe what this entity represents..."
          rows="2"
        ></textarea>
      </div>

      <!-- Source config -->
      <div class="max-w-md space-y-4">
        <div>
          <label class="mb-1 block text-sm font-medium">Project</label>
          <div class="flex gap-2">
            <div class="flex-1">
              <SearchSelect
                :model-value="datasetProject"
                :options="projectOptions"
                placeholder="Select project..."
                search-placeholder="Search projects..."
                empty-text="No projects found"
                @update:model-value="(val: string) => { datasetProject = val; datasetName = ''; updateDatasetRef(); emit('project-change', val) }"
              />
            </div>
            <button
              v-if="loadingProjects"
              class="rounded-md border px-2 py-1 text-muted-foreground"
              disabled
            >
              <DkuSpinner size="md" />
            </button>
          </div>
        </div>
        <div>
          <label class="mb-1 block text-sm font-medium">Dataset</label>
          <div class="flex gap-2">
            <div class="flex-1">
              <SearchSelect
                :model-value="datasetName"
                :options="datasetOptions"
                placeholder="Select dataset..."
                search-placeholder="Search datasets..."
                empty-text="No datasets found"
                :disabled="!datasetProject"
                @update:model-value="(val: string) => { datasetName = val; updateDatasetRef(); emit('dataset-change') }"
              />
            </div>
            <button
              v-if="loadingDatasets[datasetProject || '']"
              class="rounded-md border px-2 py-1 text-muted-foreground"
              disabled
            >
              <DkuSpinner size="md" />
            </button>
          </div>
        </div>
      </div>

      <!-- Primary Key -->
      <div>
        <label class="mb-1 block text-sm font-medium">Primary Key</label>
        <p class="mb-2 text-xs text-muted-foreground">Attributes that uniquely identify the Entity</p>
        <div v-if="attributeNameOptions.length === 0" class="text-sm text-muted-foreground">
          Add attributes with names to configure primary key
        </div>
        <div v-else class="max-w-md">
          <MultiSelect
            v-model="primaryKeyValue"
            :options="attributeNameOptions"
            placeholder="Select primary key attributes..."
            search-placeholder="Search attributes..."
            empty-text="No attributes found"
          />
        </div>
      </div>

      <!-- Columns indicator -->
      <div v-if="loadingColumns" class="flex items-center gap-2 text-sm text-muted-foreground">
        <DkuSpinner size="md" />
        Loading columns...
      </div>
      <div v-else-if="columns.length > 0" class="text-sm text-muted-foreground">
        {{ columns.length }} columns available
      </div>

      <!-- Attributes -->
      <div>
        <div class="flex items-center justify-between">
          <button
            class="flex items-center gap-2 text-sm font-medium hover:text-foreground"
            @click="toggleSection('attributes')"
          >
            <i
              class="dku-icon-chevron-right-16 transition-transform duration-[400ms]"
              :class="{ 'rotate-90': sectionsExpanded.attributes }"
            />
            Attributes
            <span class="rounded-full bg-muted px-1.5 py-0.5 text-xs font-normal text-muted-foreground">
              {{ entity.attributes.length }}
            </span>
          </button>
          <button
            v-show="sectionsExpanded.attributes"
            class="btn-tertiary"
            @click="addAttribute"
          >
            + Add Attribute
          </button>
        </div>

        <div
          class="grid transition-[grid-template-rows] duration-[400ms] ease-out"
          :class="sectionsExpanded.attributes ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'"
        >
          <div class="overflow-hidden">
            <div class="mt-3 overflow-x-auto">
          <div v-if="entity.attributes.length === 0" class="text-sm text-muted-foreground">
            No attributes. Select a dataset to auto-populate.
          </div>
          <Table v-else class="w-full table-fixed rounded-lg border">
            <colgroup>
              <col style="width: 15%" />
              <col style="width: 30%" />
              <col style="width: 10%" />
              <col style="width: auto" />
              <col style="width: 70px" />
              <col style="width: 70px" />
              <col style="width: 60px" />
            </colgroup>
            <TableHeader class="bg-muted/50">
              <TableRow>
                <TableHead>
                  <Tooltip>
                    <TooltipTrigger as-child><span>Name</span></TooltipTrigger>
                    <TooltipContent>Semantic attribute name</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead>
                  <Tooltip>
                    <TooltipTrigger as-child><span>Source</span></TooltipTrigger>
                    <TooltipContent>Column reference or SQL expression</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead>
                  <Tooltip>
                    <TooltipTrigger as-child><span>Type</span></TooltipTrigger>
                    <TooltipContent>SQL data type</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead>
                  <Tooltip>
                    <TooltipTrigger as-child><span>Description</span></TooltipTrigger>
                    <TooltipContent>Human-readable description</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead class="text-center">
                  <Tooltip>
                    <TooltipTrigger as-child><span>Resolve</span></TooltipTrigger>
                    <TooltipContent>Use attribute values to auto correct user query terms</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead class="text-center">
                  <Tooltip>
                    <TooltipTrigger as-child><span>Values</span></TooltipTrigger>
                    <TooltipContent>Include distinct values of the attribute in the LLM SQL generation prompt</TooltipContent>
                  </Tooltip>
                </TableHead>
                <TableHead class="text-right">Actions</TableHead>
              </TableRow>
              <!-- Filter row -->
              <TableRow class="bg-muted/30">
                <TableHead class="p-1">
                  <input
                    v-model="attributeFilters.name"
                    type="text"
                    class="w-full rounded border border-input bg-background px-2 py-1 text-sm font-normal"
                    placeholder="Filter..."
                  />
                </TableHead>
                <TableHead class="p-1">
                  <input
                    v-model="attributeFilters.source"
                    type="text"
                    class="w-full rounded border border-input bg-background px-2 py-1 text-sm font-normal"
                    placeholder="Filter..."
                  />
                </TableHead>
                <TableHead class="p-1">
                  <input
                    v-model="attributeFilters.type"
                    type="text"
                    class="w-full rounded border border-input bg-background px-2 py-1 text-sm font-normal"
                    placeholder="Filter..."
                  />
                </TableHead>
                <TableHead class="p-1">
                  <input
                    v-model="attributeFilters.description"
                    type="text"
                    class="w-full rounded border border-input bg-background px-2 py-1 text-sm font-normal"
                    placeholder="Filter..."
                  />
                </TableHead>
                <TableHead></TableHead>
                <TableHead></TableHead>
                <TableHead></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow
                v-for="{ attr, originalIndex } in filteredAttributes"
                :key="originalIndex"
                class="group"
              >
                <!-- Attribute name -->
                <TableCell class="overflow-hidden p-1">
                  <div class="space-y-1">
                    <input
                      v-model="attr.name"
                      type="text"
                      class="w-full truncate rounded border bg-background px-2 py-1 text-sm"
                      :class="isAttributeNameMissing(attr) ? 'border-destructive' : 'border-input'"
                      placeholder="Attribute name"
                    />
                    <p v-if="isAttributeNameMissing(attr)" class="text-xs text-destructive">
                      Name is required
                    </p>
                  </div>
                </TableCell>
                <!-- Source (column or expression) -->
                <TableCell class="overflow-hidden p-1">
                  <div class="flex items-start gap-1">
                    <select
                      :value="getAttributeMode(attr)"
                      class="shrink-0 rounded border border-input bg-background px-1 py-1 text-xs"
                      @change="(event) => setAttributeMode(attr, (event.target as HTMLSelectElement).value as 'COLUMN' | 'EXPRESSION')"
                    >
                      <option value="COLUMN">Column</option>
                      <option value="EXPRESSION">Expression</option>
                    </select>
                    <div v-if="getAttributeMode(attr) === 'COLUMN'" class="min-w-0 flex-1">
                      <SearchSelect
                        :model-value="attr.column || ''"
                        :options="columnOptions"
                        placeholder="Select column..."
                        search-placeholder="Search columns..."
                        empty-text="No columns found"
                        @update:model-value="(val: string) => handleColumnSelect(originalIndex, val)"
                      />
                      <p v-if="isAttributeColumnMissing(attr)" class="mt-1 text-xs text-destructive">
                        Column is required
                      </p>
                    </div>
                    <div v-else class="min-w-0 flex-1">
                      <Tooltip>
                        <TooltipTrigger as-child>
                          <input
                            :value="attr.pseudoSQLExpression || ''"
                            @input="(event) => setAttributeExpression(attr, (event.target as HTMLInputElement).value)"
                            type="text"
                            class="w-full truncate rounded border px-2 py-1 font-mono text-sm"
                            :class="isAttributeExpressionMissing(attr) ? 'border-destructive' : 'border-input bg-background'"
                            placeholder="SQL expression..."
                          />
                        </TooltipTrigger>
                        <TooltipContent v-if="(attr.pseudoSQLExpression || '').length > 15">
                          {{ attr.pseudoSQLExpression }}
                        </TooltipContent>
                      </Tooltip>
                      <p v-if="isAttributeExpressionMissing(attr)" class="mt-1 text-xs text-destructive">
                        Expression is required
                      </p>
                    </div>
                  </div>
                </TableCell>
                <!-- Type (readonly) -->
                <TableCell class="overflow-hidden p-1">
                  <input
                    v-model="attr.dssType"
                    type="text"
                    class="w-full truncate rounded border border-input bg-muted/50 px-2 py-1 text-sm"
                    placeholder="type"
                    readonly
                  />
                </TableCell>
                <!-- Description with tooltip -->
                <TableCell class="overflow-hidden p-1">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <input
                        v-model="attr.description"
                        type="text"
                        class="w-full truncate rounded border border-input bg-background px-2 py-1 text-sm"
                        placeholder="Description..."
                      />
                    </TooltipTrigger>
                    <TooltipContent v-if="attr.description && attr.description.length > 20">
                      {{ attr.description }}
                    </TooltipContent>
                  </Tooltip>
                </TableCell>
                <!-- Resolve checkbox -->
                <TableCell class="p-1 text-center">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <input
                        v-model="attr.resolveInUserRequests"
                        type="checkbox"
                        class="h-4 w-4 rounded border-input"
                        :disabled="!isSimpleColumn(attr)"
                        :class="{ 'opacity-50 cursor-not-allowed': !isSimpleColumn(attr) }"
                        @change="() => syncDistinctValues(attr)"
                      />
                    </TooltipTrigger>
                    <TooltipContent>{{ !isSimpleColumn(attr) ? 'Computed expressions cannot be indexed for term resolution' : 'Enable term resolution for fuzzy matching' }}</TooltipContent>
                  </Tooltip>
                </TableCell>
                <!-- Values button -->
                <TableCell class="p-1 text-center">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="relative rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
                        @click="emit('open-values-modal', originalIndex)"
                      >
                        <i class="dku-icon-list-bulleted-16" />
                        <!-- Manual values badge -->
                        <span
                          v-if="attr.manualValues?.length"
                          class="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[10px] text-primary-foreground"
                        >
                          {{ attr.manualValues.length > 99 ? '99+' : attr.manualValues.length }}
                        </span>
                        <!-- Auto mode badge -->
                        <span
                          v-else-if="attr.distinctValuesHandlingMode === 'AUTO_INDEX' || attr.indexDistinctValues"
                          class="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-blue-500 px-1 text-[10px] text-white"
                        >
                          A
                        </span>
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <template v-if="attr.manualValues?.length">{{ attr.manualValues.length }} manual values</template>
                      <template v-else-if="attr.distinctValuesHandlingMode === 'AUTO_INDEX' || attr.indexDistinctValues">Auto sample values</template>
                      <template v-else>Configure sample values</template>
                    </TooltipContent>
                  </Tooltip>
                </TableCell>
                <!-- Delete button (visible on hover) -->
                <TableCell class="p-1 text-right">
                  <Tooltip>
                    <TooltipTrigger as-child>
                      <button
                        class="rounded p-1 text-destructive opacity-0 transition-opacity hover:bg-destructive/10 group-hover:opacity-100"
                        @click="openDeleteAttributeDialog(originalIndex)"
                      >
                        <i class="dku-icon-trash-16" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent>Delete</TooltipContent>
                  </Tooltip>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
            </div>
          </div>
        </div>
      </div>

      <!-- Metrics -->
      <div>
        <div class="flex items-center justify-between">
          <button
            class="flex items-center gap-2 text-sm font-medium hover:text-foreground"
            @click="toggleSection('metrics')"
          >
            <i
              class="dku-icon-chevron-right-16 transition-transform duration-[400ms]"
              :class="{ 'rotate-90': sectionsExpanded.metrics }"
            />
            Metrics
            <span class="rounded-full bg-muted px-1.5 py-0.5 text-xs font-normal text-muted-foreground">
              {{ entity.metrics.length }}
            </span>
          </button>
          <button
            v-show="sectionsExpanded.metrics"
            class="btn-tertiary"
            @click="addMetric"
          >
            + Add Metric
          </button>
        </div>
        <div
          class="grid transition-[grid-template-rows] duration-[400ms] ease-out"
          :class="sectionsExpanded.metrics ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'"
        >
          <div class="overflow-hidden">
            <div class="mt-3">
              <div v-if="entity.metrics.length === 0" class="text-sm text-muted-foreground">
                No metrics
              </div>
              <div v-else class="space-y-3">
                <div
                  v-for="(metric, metricIndex) in entity.metrics"
                  :key="metricIndex"
                  class="rounded border bg-muted/30 p-3"
                >
                  <div class="flex items-center gap-2 mb-2">
                    <input
                      v-model="metric.name"
                      type="text"
                      class="w-40 rounded border border-input bg-background px-2 py-1 text-sm font-medium"
                      placeholder="Name of the metric"
                    />
                    <Tooltip>
                      <TooltipTrigger as-child>
                        <button
                          class="ml-auto rounded p-1 text-destructive hover:bg-destructive/10"
                          @click="openDeleteMetricDialog(metricIndex)"
                        >
                          <i class="dku-icon-trash-16" />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent>Delete</TooltipContent>
                    </Tooltip>
                  </div>

                  <div class="mb-2">
                    <input
                      v-model="metric.pseudoSQLExpression"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1.5 text-sm font-mono"
                      placeholder="SQL expression"
                    />
                  </div>

                  <div class="mb-2">
                    <input
                      v-model="metric.description"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1.5 text-sm"
                      placeholder="Description of what this metric calculates..."
                    />
                  </div>

                  <!-- Metric instructions -->
                  <div class="mb-2">
                    <input
                      v-model="metric.llmInstructions"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1 text-xs"
                      placeholder="LLM instruction for this metric..."
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Filters -->
      <div>
        <div class="flex items-center justify-between">
          <button
            class="flex items-center gap-2 text-sm font-medium hover:text-foreground"
            @click="toggleSection('filters')"
          >
            <i
              class="dku-icon-chevron-right-16 transition-transform duration-[400ms]"
              :class="{ 'rotate-90': sectionsExpanded.filters }"
            />
            Filters
            <span class="rounded-full bg-muted px-1.5 py-0.5 text-xs font-normal text-muted-foreground">
              {{ entity.filters.length }}
            </span>
          </button>
          <button
            v-show="sectionsExpanded.filters"
            class="btn-tertiary"
            @click="addFilter"
          >
            + Add Filter
          </button>
        </div>
        <div
          class="grid transition-[grid-template-rows] duration-[400ms] ease-out"
          :class="sectionsExpanded.filters ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'"
        >
          <div class="overflow-hidden">
            <div class="mt-3">
              <div v-if="entity.filters.length === 0" class="text-sm text-muted-foreground">
                No filters
              </div>
              <div v-else class="space-y-3">
                <div
                  v-for="(filter, filterIndex) in entity.filters"
                  :key="filterIndex"
                  class="rounded border bg-muted/30 p-3"
                >
                  <div class="flex items-center gap-2 mb-2">
                    <input
                      v-model="filter.name"
                      type="text"
                      class="w-40 rounded border border-input bg-background px-2 py-1 text-sm font-medium"
                      placeholder="Name of the filter"
                    />
                    <Tooltip>
                      <TooltipTrigger as-child>
                        <button
                          class="ml-auto rounded p-1 text-destructive hover:bg-destructive/10"
                          @click="openDeleteFilterDialog(filterIndex)"
                        >
                          <i class="dku-icon-trash-16" />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent>Delete</TooltipContent>
                    </Tooltip>
                  </div>
                  <div class="mb-2">
                    <input
                      v-model="filter.pseudoSQLExpression"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1.5 text-sm font-mono"
                      placeholder="SQL expression"
                    />
                  </div>
                  <div class="mb-2">
                    <input
                      v-model="filter.description"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1.5 text-sm"
                      placeholder="Description..."
                    />
                  </div>
                  <!-- Filter instructions -->
                  <div>
                    <input
                      v-model="filter.llmInstructions"
                      type="text"
                      class="w-full rounded border border-input bg-background px-2 py-1 text-xs"
                      placeholder="LLM instruction for this filter..."
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Delete Attribute Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteAttributeDialog"
      title="Delete Attribute"
      :description="`Are you sure you want to delete attribute '${itemToDelete?.name}'?`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDeleteAttribute"
    />

    <!-- Delete Metric Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteMetricDialog"
      title="Delete Metric"
      :description="`Are you sure you want to delete metric '${itemToDelete?.name}'?`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDeleteMetric"
    />

    <!-- Delete Filter Dialog -->
    <ConfirmDialog
      v-model:open="showDeleteFilterDialog"
      title="Delete Filter"
      :description="`Are you sure you want to delete filter '${itemToDelete?.name}'?`"
      confirm-text="Delete"
      cancel-text="Cancel"
      variant="destructive"
      @confirm="handleConfirmDeleteFilter"
    />
  </div>
</template>
