<script>
    import SchemaLayout from "../../layouts/SchemaLayout.svelte";
    import Sortable from "../../common/Sortable.svelte";
    import DeleteButton from "../../common/DeleteButton.svelte";
    import { post } from "../../modules/remote";
    import { getApp } from "../../app";
    let { channel, user, data } = $props();
    const app = getApp();

    function handleSchemaCreate(e) {
        e.preventDefault();
        post(
            channel.lucentUrl + "/schemas/update",
            {
                id: data.schema.id,
                name: data.schema.name,
                alias: data.schema.alias,
                revisions: data.schema.revisions,
            },
            (data, err) => {
                if (err.isEmpty()) {
                    Turbo.visit(channel.lucentUrl + "/schemas");
                }
            },
        );
    }

    function handleDelete() {
        post(
            app.url("schemas/delete"),
            {
                schemaId: data.schema.id,
            },
            (data, err) => {
                if (err.isEmpty()) {
                    Turbo.visit(app.url("schemas"));
                } else {
                    console.log(err);
                }
            },
        );
    }
</script>

<SchemaLayout {body} {channel} {user}></SchemaLayout>
{#snippet body()}
    <h3>Edit Schema</h3>

    <form onsubmit={handleSchemaCreate}>
        <fieldset>
            <label>
                Name
                <input
                    bind:value={data.schema.name}
                    placeholder="ex. Blog Posts"
                    minlength="2"
                    maxlength="30"
                    required
                />
                <small id="alias-helper">Plural is recommended</small>
            </label>
            <label>
                Alias
                <input
                    bind:value={data.schema.alias}
                    placeholder="ex. blog_posts"
                    minlength="2"
                    maxlength="30"
                    required
                    aria-describedby="alias-helper"
                />
                <small id="alias-helper">
                    Developers will use this to reference the field
                </small>
            </label>
            <label>
                Revision number
                <input
                    bind:value={data.schema.revisions}
                    type="number"
                    required
                    aria-describedby="revision-helper"
                />
                <small id="revision-helper">
                    How many revisions per document will be kept
                </small>
            </label>
        </fieldset>

        <button type="submit">Update</button>
    </form>

    <DeleteButton onDelete={handleDelete}>
        {#snippet text()}
            Delete schema
        {/snippet}
    </DeleteButton>
{/snippet}
