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

const warrenRoute = useWarrenRoute();
const dialog = useCreateDirectoryDialog();

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

async function submit() {
    if (!directoryNameValid.value || creating.value) {
        return;
    }

    creating.value = true;

    const { success } = await createDirectory(warrenRoute.value, dialog.value);

    creating.value = false;

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

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

<template>
    <Dialog v-model:open="dialog.open">
        <DialogTrigger as-child>
            <slot />
        </DialogTrigger>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>Create a directory</DialogTitle>
                <DialogDescription
                    >Give your directory a 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 || creating"
                    @click="submit"
                    >Create</Button
                >
            </DialogFooter>
        </DialogContent>
    </Dialog>
</template>
