<script setup lang="ts">
const props = defineProps<{
  visible: boolean
  group?: any | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void
  (e: 'saved'): void
}>()

const connections = useConnectionStore()

const form = ref({
  name: '',
  parentId: null as number | null,
})

const saving = ref(false)
const error = ref('')

const isEdit = computed(() => !!props.group?.id)
const title = computed(() => isEdit.value ? 'Edit Group' : 'New Group')

const parentOptions = computed(() => {
  const options: { label: string; value: number | null }[] = [{ label: 'No Parent (top-level)', value: null }]
  const addGroups = (groups: any[], prefix = '') => {
    for (const g of groups) {
      if (isEdit.value && g.id === props.group?.id) continue
      options.push({ label: prefix + g.name, value: g.id })
      if (g.children?.length) addGroups(g.children, prefix + g.name + ' / ')
    }
  }
  addGroups(connections.groups)
  return options
})

watch(() => props.visible, (v) => {
  if (v) {
    form.value = {
      name: props.group?.name || '',
      parentId: props.group?.parentId ?? null,
    }
    error.value = ''
  }
})

function close() {
  emit('update:visible', false)
}

async function save() {
  error.value = ''
  saving.value = true
  try {
    if (isEdit.value) {
      await connections.updateGroup(props.group.id, form.value)
    } else {
      await connections.createGroup(form.value)
    }
    emit('saved')
    close()
  } catch (e: any) {
    error.value = e.data?.message || 'Failed to save group'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <div v-if="visible" class="fixed inset-0 z-[9999] flex items-center justify-center">
    <!-- Backdrop -->
    <div class="absolute inset-0 bg-black/70" @click="close" />
    <!-- Dialog -->
    <div class="relative bg-gray-900 border border-gray-700 rounded-lg shadow-2xl w-[380px] max-h-[90vh] overflow-y-auto">
      <!-- Header -->
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-800">
        <h3 class="text-lg font-semibold text-white">{{ title }}</h3>
        <button @click="close" class="text-gray-500 hover:text-white text-xl leading-none">&times;</button>
      </div>
      <!-- Body -->
      <div class="px-5 py-4 space-y-4">
        <div>
          <label class="block text-sm text-gray-400 mb-1">Group Name *</label>
          <input v-model="form.name" type="text" placeholder="Production Servers" autofocus
            class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-white focus:border-sky-500 focus:outline-none" />
        </div>
        <div>
          <label class="block text-sm text-gray-400 mb-1">Parent Group</label>
          <select v-model="form.parentId"
            class="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-white focus:border-sky-500 focus:outline-none">
            <option v-for="opt in parentOptions" :key="String(opt.value)" :value="opt.value">{{ opt.label }}</option>
          </select>
        </div>
        <p v-if="error" class="text-red-400 text-sm">{{ error }}</p>
      </div>
      <!-- Footer -->
      <div class="flex justify-end gap-2 px-5 py-4 border-t border-gray-800">
        <button @click="close" class="px-4 py-2 text-sm text-gray-400 hover:text-white rounded">Cancel</button>
        <button @click="save" :disabled="saving || !form.name"
          class="px-4 py-2 text-sm bg-sky-600 hover:bg-sky-700 text-white rounded disabled:opacity-50">
          {{ saving ? 'Saving...' : 'Save' }}
        </button>
      </div>
    </div>
  </div>
</template>
