<template>
  <Dialog
    :visible="visible"
    @update:visible="$emit('update:visible', $event)"
    header="Spalten anpassen"
    :modal="true"
    :style="{ width: '600px' }"
  >
    <div class="flex flex-col gap-3">
      <p class="text-500 mb-2">Wählen Sie die anzuzeigenden Spalten aus und ziehen Sie sie, um die Reihenfolge zu ändern:</p>
      
      <div class="flex flex-col gap-2">
        <div 
          v-for="(column, index) in localColumns" 
          :key="column.key" 
          class="flex items-center gap-2 p-3 border rounded-md hover-row cursor-move"
          draggable="true"
          @dragstart="onDragStart(index)"
          @dragover.prevent
          @drop="onDrop(index)"
        >
          <i class="pi pi-bars text-500"></i>
          <Checkbox 
            :inputId="'col-' + column.key" 
            v-model="localVisibility[column.key]" 
            :binary="true"
          />
          <label :for="'col-' + column.key" class="cursor-pointer flex-1">{{ column.label }}</label>
        </div>
      </div>
    </div>
    
    <template #footer>
      <Button label="Abbrechen" outlined @click="cancel" />
      <Button label="Speichern" @click="save" />
    </template>
  </Dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import Dialog from 'primevue/dialog'
import Button from 'primevue/button'
import Checkbox from 'primevue/checkbox'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  columns: {
    type: Array,
    required: true
  },
  visibleColumns: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:visible', 'update:columns', 'update:visibleColumns', 'save'])

// Local copies for editing
const localColumns = ref([...props.columns])
const localVisibility = ref({ ...props.visibleColumns })

// Watch for prop changes
watch(() => props.columns, (newVal) => {
  localColumns.value = [...newVal]
}, { deep: true })

watch(() => props.visibleColumns, (newVal) => {
  localVisibility.value = { ...newVal }
}, { deep: true })

// Drag and drop for column reordering
let draggedIndex = null

const onDragStart = (index) => {
  draggedIndex = index
}

const onDrop = (dropIndex) => {
  if (draggedIndex === null || draggedIndex === dropIndex) return
  
  const columns = [...localColumns.value]
  const draggedItem = columns[draggedIndex]
  
  columns.splice(draggedIndex, 1)
  columns.splice(dropIndex, 0, draggedItem)
  
  localColumns.value = columns
  draggedIndex = null
}

const save = () => {
  emit('update:columns', localColumns.value)
  emit('update:visibleColumns', localVisibility.value)
  emit('save')
}

const cancel = () => {
  // Reset local changes
  localColumns.value = [...props.columns]
  localVisibility.value = { ...props.visibleColumns }
  emit('update:visible', false)
}
</script>
