<script setup lang="ts">
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
} from '@/components/ui/dialog';
import { renameWarrenEntry } from '~/lib/api/warrens';

const warrenStore = useWarrenStore();
const dialog = useRenameDirectoryDialog();

const renaming = ref(false);
const directoryNameValid = computed(() => dialog.value.trim().length > 0);

async function submit() {
    if (
        dialog.entry == null ||
        !directoryNameValid.value ||
        renaming.value ||
        warrenStore.current == null
    ) {
        return;
    }

    renaming.value = true;

    const { success } = await renameWarrenEntry(
        warrenStore.current.warrenId,
        warrenStore.current.path,
        dialog.entry.name,
        dialog.value
    );

    renaming.value = false;

    if (success) {
        dialog.reset();
    }
}

function onKeyDown(e: KeyboardEvent) {
    if (e.key === 'Enter') {
        submit();
    }
}
</script>

<template>
    <Dialog v-model:open="dialog.open">
        <DialogContent>
            <DialogHeader>
                <DialogTitle>Rename your directory</DialogTitle>
                <DialogDescription
                    >Give your directory a new memorable name</DialogDescription
                >
            </DialogHeader>

            <Input
                v-model="dialog.value"
                type="text"
                name="directory-name"
                placeholder="my-awesome-directory"
                aria-required="true"
                autocomplete="off"
                required
                @keydown="onKeyDown"
            />

            <DialogFooter>
                <Button
                    :disabled="!directoryNameValid || renaming"
                    @click="submit"
                    >Rename</Button
                >
            </DialogFooter>
        </DialogContent>
    </Dialog>
</template>
