<script lang="ts">
    import { get_coords } from "$lib/gps"
    import { X, Check, Plus } from "@lucide/svelte"
    import { onMount } from "svelte"

    let privateRoom: boolean = $state(true)
    let coord = $state({ latitude: 0, longitude: 0 })
    let creating: boolean = $state(false)

    let name: string = $state()
    let range: number = $state()
    let pin: number = $state()

    async function createRoom() {
        if (creating) {
            return
        }

        if (!name) {
            return
        }

        creating = true

        const res = await fetch(
            `/api/room/new?name=${encodeURIComponent(name)}&coords=${coord.latitude},${coord.longitude}&range=${encodeURIComponent(range ?? "100")}&pin=${encodeURIComponent(pin ?? "")}`,
            { method: "POST" }
        )

        const json = await res.json()

        window.location.href = `/admin/${json.room_id}`
    }

    onMount(async () => {
        const res = await get_coords()
        coord = res.coords ?? { latitude: 46.6769043, longitude: 11.1851585 }
    })
</script>

<form class="flex flex-col items-center">
    <h1 class="text-4xl my-10">Create Room</h1>

    <div class="flex flex-col gap-3 w-1/2">
        <input
            bind:value={name}
            placeholder="Room name (Required)"
            class="{name
                ? ''
                : 'border-2 border-red-500'} p-2 text-xl rounded-md bg-light-pine-overlay hover:bg-dark-pine-base/20 dark:bg-dark-pine-overlay hover:dark:bg-light-pine-base/20 duration-100 outline-none focus:ring-2"
        />

        <input
            bind:value={range}
            type="number"
            min="10"
            placeholder="Range (in meters)"
            class="p-2 text-xl rounded-md border-dark-pine-muted bg-light-pine-overlay hover:bg-dark-pine-base/20 dark:bg-dark-pine-overlay hover:dark:bg-light-pine-base/20 duration-100 outline-none focus:ring-2"
        />

        <p>
            Room Coordinates:
            <span>{coord.latitude},{coord.longitude}</span>
        </p>

        <input
            bind:value={pin}
            type="number"
            max="9999"
            placeholder="PIN  (none if public)"
            class="p-2 text-xl rounded-md border-dark-pine-muted bg-light-pine-overlay hover:bg-dark-pine-base/20 dark:bg-dark-pine-overlay hover:dark:bg-light-pine-base/20 duration-100 outline-none focus:ring-2"
        />

        <button
            type="button"
            class="cursor-pointer flex flex-row items-center justify-center gap-3 border border-dark-pine-muted bg-light-pine-overlay hover:bg-dark-pine-base/20 dark:bg-dark-pine-overlay hover:dark:bg-light-pine-base/20 duration-100 rounded-lg h-10 font-bold"
            onclick={createRoom}
        >
            CREA
            <Plus />
        </button>
    </div>
</form>
