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

    const { data } = $props();

    const synchronizer = $state({
        isRunning: false,
        syncingPrintfulProductIds: [] as number[],
        poll: async function () {
            const res = await api.products.sync.get();
            if (res.error) {
                synchronizer.isRunning = false;
                synchronizer.syncingPrintfulProductIds = [];
            } else {
                synchronizer.isRunning = true;
                synchronizer.syncingPrintfulProductIds =
                    res.data.syncingPrintfulProductIds;
            }
        },
        startPolling: () => {
            const intervalId = setInterval(async () => {
                await synchronizer.poll();
                if (!synchronizer.isRunning) clearInterval(intervalId);
            }, 100);
        },
        syncAll: async () => {
            synchronizer.startPolling();
            await api.products.sync.post();
        },
        sync: async (printfulProductId: number) => {
            synchronizer.startPolling();
            await api.products.sync({ printfulProductId }).post();
        },
    });

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

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

{#await data.products.printful}
    <p>Loading...</p>
{:then printfulProducts}
    <button
        disabled={synchronizer.isRunning}
        onclick={() => synchronizer.syncAll()}
        class="btn btn-xl mb-5"
    >
        {#if synchronizer.isRunning}
            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 printfulProducts as printfulProduct}
                    <tr class="hover:bg-base-300">
                        <td
                            ><button
                                onclick={async () => {
                                    const res = await api
                                        .products({
                                            printfulProductId:
                                                printfulProduct.id,
                                        })
                                        .get();
                                    console.log(res.data);
                                }}
                                class="cursor-pointer underline"
                            >
                                {printfulProduct.name}
                            </button></td
                        >
                        <td>
                            {#await isProductSynced(printfulProduct) then isSynced}
                                {#if synchronizer.syncingPrintfulProductIds.includes(printfulProduct.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.isRunning}
                                onclick={() =>
                                    synchronizer.sync(printfulProduct.id)}
                                class="btn"
                            >
                                Sync
                            </button>
                        </td>
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>
{:catch error}
    <p>Something went wrong: {error.message}</p>
{/await}
