import { defineStore } from 'pinia';
import { ref } from 'vue';
import { scraperService, PriceRecord } from '../services/scraperService';
import { useNotification } from '@kyvg/vue3-notification';

export const useOilPriceStore = defineStore('oilPrice', () => {
    const prices = ref<PriceRecord[]>([]);
    const loading = ref(false);
    const error = ref<string | null>(null);
    const { notify } = useNotification();
    let intervalId: number | null = null;

    const fetchPrices = async () => {
        loading.value = true;
        error.value = null;
        try {
            const response = await scraperService.getLatestPrices();
            if (response.data && Array.isArray(response.data)) {
                const newPrices = response.data;

                // Check for price changes since last visit
                checkPriceChange(newPrices);

                prices.value = newPrices;

                // Store current prices for next time
                localStorage.setItem('last_oil_prices', JSON.stringify(newPrices));
                localStorage.setItem('last_price_check', new Date().toISOString());
            }
        } catch (err) {
            console.error('Failed to fetch oil prices:', err);
            // Don't show error to user as this is a background feature
            error.value = 'Failed to load oil prices';
        } finally {
            loading.value = false;
        }
    };

    const startPolling = () => {
        if (intervalId) return;
        fetchPrices(); // Initial fetch
        intervalId = window.setInterval(fetchPrices, 1 * 60 * 1000);
    };

    const stopPolling = () => {
        if (intervalId) {
            clearInterval(intervalId);
            intervalId = null;
        }
    };

    const checkPriceChange = (newPrices: PriceRecord[]) => {
        const stored = localStorage.getItem('last_oil_prices');
        if (!stored) return;

        try {
            const oldPrices: PriceRecord[] = JSON.parse(stored);

            // Find lowest price in old and new to compare generally? 
            // Or simply alert if ANY price changed significantly?
            // Let's find the lowest price change which is most relevant.

            const getLowest = (list: PriceRecord[]) => Math.min(...list.map(p => p.price_decimal));

            const oldLow = getLowest(oldPrices);
            const newLow = getLowest(newPrices);

            if (oldLow && newLow && oldLow !== newLow) {
                const diff = newLow - oldLow;
                const trend = diff > 0 ? 'up' : 'down';
                const type = diff > 0 ? 'warn' : 'success'; // Green for price drop!

                notify({
                    title: 'Oil Price Update',
                    text: `Prices have gone ${trend} by $${Math.abs(diff).toFixed(3)}. Lowest: $${newLow}`,
                    type: type,
                    duration: 10000,
                });
            }
        } catch (e) {
            console.error('Error checking price changes', e);
        }
    };

    return {
        prices,
        loading,
        error,
        fetchPrices,
        startPolling,
        stopPolling
    };
});
