// resources/js/Modules/TakingOrder/Composables/useOfflineManager.js
import { ref, computed } from "vue";
import localforage from "localforage";

export function useOfflineManager() {
    const isOnline = ref(navigator.onLine);
    const isSyncing = ref(false);
    const pendingOrders = ref([]);

    // Setup IndexedDB
    const db = localforage.createInstance({
        name: "sfa-offline",
        storeName: "pending-orders",
    });

    // Cek status online/offline
    window.addEventListener("online", () => {
        isOnline.value = true;
        syncPendingOrders();
    });

    window.addEventListener("offline", () => {
        isOnline.value = false;
    });

    // Load pending orders from IndexedDB
    const loadPendingOrders = async () => {
        try {
            const keys = await db.keys();
            const orders = [];
            for (const key of keys) {
                const order = await db.getItem(key);
                orders.push(order);
            }
            pendingOrders.value = orders;
        } catch (error) {
            console.error("Load pending orders failed:", error);
        }
    };

    // Save order to IndexedDB (offline)
    const saveOrderOffline = async (orderData) => {
        try {
            const id =
                "order_" +
                Date.now() +
                "_" +
                Math.random().toString(36).substr(2, 9);
            const order = {
                id: id,
                ...orderData,
                status: "pending",
                created_at: new Date().toISOString(),
                synced: false,
            };
            await db.setItem(id, order);
            await loadPendingOrders();
            return { success: true, id: id, offline: true };
        } catch (error) {
            console.error("Save offline failed:", error);
            throw error;
        }
    };

    // Sync pending orders to server
    const syncPendingOrders = async () => {
        if (!isOnline.value || isSyncing.value) return;

        isSyncing.value = true;

        try {
            const keys = await db.keys();
            let syncedCount = 0;

            for (const key of keys) {
                const order = await db.getItem(key);
                if (order && !order.synced) {
                    // Kirim ke server
                    const response = await fetch(
                        "/sales/taking-order/order/store",
                        {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json",
                                "X-CSRF-TOKEN": document.querySelector(
                                    'meta[name="csrf-token"]',
                                )?.content,
                            },
                            body: JSON.stringify({
                                customer_id: order.customer_id,
                                items: order.items,
                                notes: order.notes || "",
                            }),
                        },
                    );

                    if (response.ok) {
                        await db.removeItem(key);
                        syncedCount++;
                    }
                }
            }

            await loadPendingOrders();

            if (syncedCount > 0) {
                // Notifikasi sukses
                showNotification(
                    `${syncedCount} order berhasil di-sync ke server`,
                );
            }

            return { success: true, syncedCount };
        } catch (error) {
            console.error("Sync failed:", error);
            showNotification(
                "Gagal sync data, akan dicoba lagi nanti",
                "error",
            );
            return { success: false, error: error.message };
        } finally {
            isSyncing.value = false;
        }
    };

    // Show notification
    const showNotification = (message, type = "success") => {
        // Gunakan toast atau alert
        if (typeof window !== "undefined" && window.toast) {
            window.toast[type](message);
        } else {
            alert(message);
        }
    };

    // Auto sync setiap 30 detik jika online
    setInterval(() => {
        if (isOnline.value) {
            syncPendingOrders();
        }
    }, 30000);

    return {
        isOnline,
        isSyncing,
        pendingOrders,
        saveOrderOffline,
        syncPendingOrders,
        loadPendingOrders,
    };
}
