<script lang="ts">
    import type { Printful } from "@blade-and-brawn/commerce";
    import { onMount } from "svelte";
    import { api } from "$lib/api.js";

    type SyncStatus = "queued" | "active" | "failed" | "succeeded" | "none";

    const { data } = $props();

    const synchronizer = $state({
        status: "none" as SyncStatus,
        syncingPProductIds: [] as number[],
        get isInProgress() {
            return this.status === "active" || this.status === "queued";
        },
        poll: async function () {
            const res = await api.products.sync.get();
            if (res.error) {
                synchronizer.status = "none";
                synchronizer.syncingPProductIds = [];
            } else {
                synchronizer.status = res.data.status;
                synchronizer.syncingPProductIds =
                    res.data.syncingPProductIds;
            }
        },
        startPolling: () => {
            const intervalId = setInterval(async () => {
                await synchronizer.poll();
                if (!synchronizer.isInProgress) clearInterval(intervalId);
            }, 100);
        },
        syncAll: async () => {
            synchronizer.startPolling();
            await api.products.sync.post();
        },
        sync: async (pProductId: number) => {
            synchronizer.startPolling();
            await api.products.sync({ pProductId }).post();
        },
    });

    onMount(async () => {
        await synchronizer.poll();
        if (synchronizer.isInProgress) {
            synchronizer.startPolling();
        }
    });

    const isProductSynced = async (
        pProduct: Printful.Products.SyncProduct,
    ) => {
        const wProducts = await data.products.webflow;
        return wProducts.some(
            (p) => p.product.id === pProduct.external_id.split("-")[0],
        );
    };
</script>

{#await data.products.printful}
    <p>Loading...</p>
{:then pProducts}
    <button
        disabled={synchronizer.isInProgress}
        onclick={() => synchronizer.syncAll()}
        class="btn btn-xl mb-5"
    >
        {#if synchronizer.isInProgress}
            Syncing...
        {:else}
            Sync all
        {/if}
    </button>
    <div class="w-full overflow-x-auto">
        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Status</th>
                    <th>Sync</th>
                </tr>
            </thead>
            <tbody>
                {#each pProducts as pProduct}
                    <tr class="hover:bg-base-300">
                        <td
                            ><button
                                onclick={async () => {
                                    const res = await api
                                        .products({
                                            pProductId:
                                                pProduct.id,
                                        })
                                        .get();
                                    console.log(res.data);
                                }}
                                class="cursor-pointer underline"
                            >
                                {pProduct.name}
                            </button></td
                        >
                        <td>
                            {#await isProductSynced(pProduct) then isSynced}
                                {#if synchronizer.syncingPProductIds.includes(pProduct.id)}
                                    <div class="badge badge-warning">
                                        Syncing...
                                    </div>
                                {:else if isSynced}
                                    <div class="badge badge-success">
                                        Synced
                                    </div>
                                {:else}
                                    <div class="badge badge-error">
                                        Desynced
                                    </div>
                                {/if}
                            {/await}
                        </td>
                        <td>
                            <button
                                disabled={synchronizer.status === "active"}
                                onclick={() =>
                                    synchronizer.sync(pProduct.id)}
                                class="btn"
                            >
                                Sync
                            </button>
                        </td>
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>
{:catch error}
    <p>Something went wrong: {error.message}</p>
{/await}
