<script>
    import SchemaLayout from "../../layouts/SchemaLayout.svelte";
    import TextFieldProps from "./TextFieldProps.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 handleUpdate(e) {
        e.preventDefault();
        post(
            app.url("fields/update"),
            {
                field: data.field,
            },
            (data, err) => {
                if (err.isEmpty()) {
                    Turbo.visit(app.url("schemas"));
                } else {
                    console.log(err);
                }
            },
        );
    }

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

<SchemaLayout {body} {channel} {user}></SchemaLayout>
{#snippet body()}
    <h3 class="header-small mb-4 mt-5">
        Edit <em>{data.field.type}</em> field {data.field.name}
    </h3>

    <form onsubmit={handleUpdate}>
        <fieldset>
            <label>
                Name
                <input
                    bind:value={data.field.name}
                    placeholder="ex. Description"
                    minlength="2"
                    maxlength="30"
                    required
                />
            </label>
            <label>
                Alias
                <input
                    bind:value={data.field.alias}
                    placeholder="ex. description"
                    minlength="2"
                    maxlength="30"
                    required
                    aria-describedby="alias-helper"
                />
                <small id="alias-helper">
                    Developers will use this to reference the field
                </small>
            </label>
        </fieldset>

        {#if data.field.type === "text"}
            <TextFieldProps field={data.field}></TextFieldProps>
        {/if}

        <button type="submit">Update</button>
    </form>
    <DeleteButton onDelete={handleDelete}>
        {#snippet text()}
            Delete field
        {/snippet}
    </DeleteButton>
{/snippet}
