<script lang="ts">
    import { getCurrentLocation } from "$lib/scripts/getLocation";
    import toast from "svelte-french-toast";
    import Card from "./Card.svelte";
    import type { CardConfig } from "./Card.types";
    import type { NearestStationResponse } from "@owlboard/ts-types";
    import { uuid } from "$lib/stores/uuid";
    import { location } from "$lib/stores/location";
    import InLineLoading from "$lib/navigation/InLineLoading.svelte";
    import { apiGet } from "$lib/scripts/apiFetch";
    import { onMount } from "svelte";
    import { nearToMeCache } from "$lib/stores/nearToMeCache";
    import LinkButton from "$lib/buttons/LinkButton.svelte";
    import ScriptButton from "$lib/buttons/ScriptButton.svelte";

    let errorMessage: string;
    let stations: NearestStationResponse[] = [];
    let blockLoading: boolean = true;

    let config: CardConfig = {
        title: "Near to Me",
        showHelp: true,
        showRefresh: true,
        helpText: "Your location may not be accurate on desktop and laptop devices.",
        onRefresh: getNearestStations,
        refreshing: false,
    };

    function turnOnLocation() {
        location.set(true);
        getCurrentLocation();
        toast.success("Done\nTo disable location, go to settings");
    }

    async function getNearestStations() {
        // Get location, then fetch nearest stations and push to `stations` variable
        config.refreshing = true;
        const currentLocation = await getCurrentLocation();
        const apiPath: string = `/api/v2/live/station/nearest/${currentLocation.latitude}/${currentLocation.longitude}`;
        try {
            const apiResponse = (await apiGet(apiPath)) as NearestStationResponse[];
            stations = apiResponse;
            nearToMeCache.set(apiResponse);
        } catch (err) {
            errorMessage = err as string;
        } finally {
            config.refreshing = false;
        }
    }

    onMount(() => {
        if ($location) {
            if (!$uuid || $uuid === "null") {
                errorMessage = "Register to use this feature";
            } else {
                if ($nearToMeCache.length) {
                    stations = $nearToMeCache;
                }
                getNearestStations();
            }
        }
        blockLoading = false;
    });
</script>

<Card {config}>
    {#if blockLoading}
        <InLineLoading />
    {:else}
    <div id="buttons">
    {#if !$uuid || $uuid === "null"}
        <LinkButton text="Register to use this feature" link="/more/reg" />
    {:else if $location}
        {#if !stations.length}
            {#if errorMessage}
                <p>{errorMessage}</p>
            {:else}
                <InLineLoading />
            {/if}
        {:else}
            {#each stations as station}
                <LinkButton text={`${station.NLCDESC} - ${station.miles}mi`} link={`/ldb?station=${station["3ALPHA"]}`} />
            {/each}
        {/if}
    {:else}
        <ScriptButton text={"Turn on Location"} fn={turnOnLocation} />
    {/if}
    </div>
    {/if}
</Card>

<style>
    #buttons {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        width: 95%;
        margin: auto;
        padding-top: 5px;
    }

    p {
        text-align: center;
        margin: auto;
    }
</style>
