<script lang="ts">
    import { ChevronDown, ChevronRight, Folder, FolderPlus, FileJson, FileText, File, FilePlus } from "lucide-svelte";
    import type { DirTree } from "./page.svelte";
    import PagesList from "./PagesList.svelte";
    import { slide } from "svelte/transition";
    import Button from "@components/ui/button/button.svelte";
    import { manager } from "./page.svelte";

    const { page, depth = 0, path }: { page: DirTree; depth?: number; path: string } = $props();

    let open = $state(false);
    let newPage = $state(false);
    let newPageName = $state("");

    let newPageInput: HTMLInputElement | undefined = $state();

    function startNewPageCreate(e: Event) {
        e.stopPropagation();
        newPage = true;
        newPageName = "";
        open = true;

        setTimeout(() => {
            newPageInput?.focus();
        }, 1);
    }

    function createNewPage(e: Event) {
        e.preventDefault();
        e.stopPropagation();

        if (newPageName.trim() === "") {
            alert("Page name cannot be empty");
            return;
        }

        if (!newPageName.match(/^[a-zA-Z0-9_\-\.]+$/)) {
            alert("Invalid page name. Only alphanumeric characters, underscores, dashes, and dots are allowed.");
            return;
        }

        if (!newPageName.endsWith(".json") && !newPageName.endsWith(".md") && !newPageName.endsWith(".mdx")) {
            newPageName += ".md";
        }

        manager
            .createPage(path + newPageName, newPageName)
            .then(() => {
                newPage = false;
                newPageName = "";
            })
            .catch((error) => {
                alert("Error creating page: " + error.message);
            });
    }
</script>

<button class={`group flex flex-row justify-between h-full w-full hover:bg-neutral-700 pl-${4 * depth}`} onclick={() => (open = !open)}>
    <div class="flex flex-row items-center">
        {#if open}
            <ChevronDown class="w-6 h-6" />
        {:else}
            <ChevronRight class="w-6 h-6" />
        {/if}
        <Folder class="mr-2 w-4 h-4" />
        {page.name}/
    </div>
    <div class="flex-row items-center hidden group-hover:flex">
        <Button variant="ghost" size="sm" class="p-0 m-0 h-6 w-6" onclick={startNewPageCreate}>
            <FilePlus class="w-3 h-3" />
        </Button>
    </div>
</button>

{#if open}
    <div transition:slide={{ duration: 200, axis: "y" }}>
        <div>
            {#if newPage}
                <button class={`flex flex-row items-center h-full py-1 w-full hover:bg-neutral-700 pl-${4 * (depth + 1)}`}>
                    {#if newPageName.endsWith(".json")}
                        <FileJson class="mr-2 w-4 h-4" />
                    {:else if newPageName.endsWith(".md") || newPageName.endsWith(".mdx")}
                        <FileText class="mr-2 w-4 h-4" />
                    {:else}
                        <File class="mr-2 w-4 h-4" />
                    {/if}
                    <form onsubmit={createNewPage}>
                        <input
                            type="text"
                            bind:value={newPageName}
                            bind:this={newPageInput}
                            onblur={() => (newPage = false)}
                            placeholder="New page name"
                            class="flex-grow bg-transparent border-none outline-none text-white"
                        />
                    </form>
                </button>
            {/if}
            {#each Object.values(page.dirs) as subPage (subPage.name)}
                <PagesList page={subPage} depth={depth + 1} path={path + subPage.name + "/"} />
            {/each}
            {#each Object.values(page.files) as file (file.id)}
                <button class={`flex flex-row items-center h-full py-1 w-full hover:bg-neutral-700 pl-${4 * (depth + 1)}`} onclick={() => manager.openPage(file.id)}>
                    {#if file.name.endsWith(".json")}
                        <FileJson class="mr-2 w-4 h-4" />
                    {:else if file.name.endsWith(".md") || file.name.endsWith(".mdx")}
                        <FileText class="mr-2 w-4 h-4" />
                    {:else}
                        <File class="mr-2 w-4 h-4" />
                    {/if}
                    {file.name}
                </button>
            {/each}
        </div>
    </div>
{/if}
