<script setup lang="ts">
import { ref } from 'vue'
import { useApp } from '@/composables/useApp'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'

const props = defineProps<{
  open: boolean
  itemPath: string
  currentName: string
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
}>()

const app = useApp()
const newName = ref('')
const isRenaming = ref(false)

function setOpen(value: boolean) {
  emit('update:open', value)
  if (value) newName.value = props.currentName
}

async function rename() {
  if (!newName.value.trim() || newName.value.trim() === props.currentName || !app.activeConnection.value) return
  isRenaming.value = true
  try {
    await app.activeConnection.value.renameItem(props.itemPath, newName.value.trim())
    setOpen(false)
  } finally {
    isRenaming.value = false
  }
}
</script>

<template>
  <Dialog :open="open" @update:open="setOpen">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle>Rename</DialogTitle>
        <DialogDescription>
          Enter a new name for "{{ currentName }}"
        </DialogDescription>
      </DialogHeader>
      <div class="space-y-2 py-2">
        <Label for="new-name">New Name</Label>
        <Input id="new-name" v-model="newName" @keydown.enter="rename" autofocus />
      </div>
      <DialogFooter>
        <Button variant="outline" @click="setOpen(false)">Cancel</Button>
        <Button @click="rename" :disabled="!newName.trim() || newName.trim() === currentName || isRenaming">
          {{ isRenaming ? 'Renaming...' : 'Rename' }}
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>
