<script lang="ts">
import {ArrowLeftSolid} from "flowbite-svelte-icons";
import {Button, Card, Input, Label, Navbar, NavBrand, NavHamburger, NavUl, Spinner} from "flowbite-svelte";
import {pageRepo} from "../../repo/repo.js";
import {mapToMap, nameRegex} from "../util.ts";
import TypeAheadSearch from "../components/TypeAheadSearch.svelte";
import {branches} from "../../stores/stores.ts";
import Editor from "./edit/Editor.svelte";

$: pagesFuture = $pageRepo.listPages(selectedBranch);

let selected: number | null = null;

let selectedBranch: string = "master";
let searchValue: string = "";

$: availableBranches = $branches.map((branch) => ({
    name: branch,
    value: branch
}))

$: console.log(availableBranches)

async function createBranch() {
    const name = prompt("Branch name:")
    if (name) {
        selected = null
        await $pageRepo.createBranch(name)
        let inter = setInterval(() => {
            branches.reload()
            if ($branches.includes(name)) {
                selectedBranch = name
                searchValue = ""
                clearInterval(inter)
            }
        }, 1000)
    }
}

async function deleteBranch(con: boolean = false) {
    if (selectedBranch !== "master") {
        let conf = con || confirm("Are you sure you want to delete this branch?")
        if(conf) {
            await $pageRepo.deleteBranch(selectedBranch)
            let inter = setInterval(() => {
                branches.reload()
                if (!$branches.includes(selectedBranch)) {
                    selectedBranch = "master"
                    searchValue = ""
                    clearInterval(inter)
                }
            }, 1000)
        }
    } else {
        alert("You can't delete the master branch")
    }
}

async function createFile() {
    let name = prompt("File name:", "pages/en/[Name]")
    if (name) {
        await $pageRepo.createFile(`${name}`, selectedBranch)
        reload()
    }
}

function reload() {
    const w = selectedBranch
    selectedBranch = "###!"
    selectedBranch = w
}

async function mergeBranch() {
    await $pageRepo.merge(selectedBranch, `Go live of ${selectedBranch}`)
    await deleteBranch(true)
}

</script>
<div class="flex flex-col h-screen overflow-scroll">
    <Navbar let:hidden let:toggle>
        <NavBrand href="#">
            <ArrowLeftSolid></ArrowLeftSolid>
            <span class="ml-4 self-center whitespace-nowrap text-xl font-semibold dark:text-white">
                Edit Pages
            </span>
        </NavBrand>
    </Navbar>
    <div class="p-4 flex-1">
        <div class="grid md:grid-cols-3 grid-cols-1 h-full gap-8">
            <Card class="h-full flex flex-col !max-w-full">
                {#await pagesFuture}
                    <Spinner />
                {:then pages}
                    <div class="border-b border-b-gray-600 pb-2 flex justify-between">
                        <TypeAheadSearch items={availableBranches} bind:selected={selectedBranch} bind:searchValue />
                        <div>
                            {#if selectedBranch !== "master"}
                                <Button on:click={mergeBranch}>Merge Branch</Button>
                            {:else}
                                <Button on:click={createBranch}>Create Branch</Button>
                            {/if}
                            <Button on:click={createFile} color="alternative">Create File</Button>
                            {#if selectedBranch !== "master"}
                                <Button on:click={deleteBranch} color="ghost">Delete Branch</Button>
                            {/if}
                        </div>
                    </div>
                    {@const pagesMap = mapToMap(pages)}
                    {#each pagesMap as [key, value]}
                        <details>
                            <summary class="p-4 transition-colors hover:bg-gray-700 cursor-pointer">{key}</summary>
                            <ul>
                                {#each value as page}
                                    {@const match = nameRegex.exec(page.path) ? nameRegex.exec(page.path)[0] : ""}
                                    {@const startIndex = page.path.indexOf(match)}
                                    {@const endIndex = startIndex + match.length}
                                    <li class="p-4 transition-colors hover:bg-gray-700 cursor-pointer" on:click|preventDefault={() => selected = page.id}>
                                        <span class:text-orange-600={selected === page.id}>{page.path.substring(0, startIndex)}</span><span class="text-white" class:!text-orange-500={selected === page.id}>{match}</span><span class:text-orange-600={selected === page.id}>{page.path.substring(endIndex, page.path.length)}</span>
                                    </li>
                                {/each}
                            </ul>
                        </details>
                    {/each}
                {:catch error}
                    <p>{error.message}</p>
                {/await}
            </Card>
            <Card class="!max-w-full" style="grid-column: 2/4">
                {#if selected}
                    <Editor pageId={selected} branch={selectedBranch} on:reload={reload} />
                {/if}
            </Card>
        </div>
    </div>
</div>