<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 directoryName = ref('');
const directoryNameValid = computed(
    () => directoryName.value.trim().length > 0
);

async function submit() {
    creating.value = true;

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

    creating.value = false;

    if (success) {
        directoryName.value = '';
        dialog.open = false;
    }
}
</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="directoryName"
                type="text"
                name="directory-name"
                placeholder="my-awesome-directory"
                aria-required="true"
                autocomplete="off"
                required
            />

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