import { ref, computed } from 'vue';
import { getFirestore, doc, getDoc, updateDoc } from 'firebase/firestore';
import { appUser, magentoUserId } from '../globals/user.js';
import { useToast } from 'vue-toastification';

export function useMySubscriptions() {
    const toast = useToast();

    // Reactive state
    const subscriptions = ref([]);
    const loading = ref(false);
    const error = ref(null);

    // Computed property to format subscriptions with additional metadata
    const formattedSubscriptions = computed(() => {
        if (!appUser.value?.topics) return [];

        return appUser.value.topics.map((cpvCode, index) => ({
            id: `${appUser.value.id}_${cpvCode}`,
            cpvCode,
            description: getCPVDescription(cpvCode),
            isActive: true, // All topics in the array are considered active
            createdAt: appUser.value.timestamp ? new Date(appUser.value.timestamp) : new Date(),
            updating: false,
            userId: appUser.value.id
        }));
    });

    // Helper function to get CPV description (can be enhanced with actual CPV data)
    function getCPVDescription(cpvCode) {
        // This could be enhanced to fetch from a CPV codes database
        // For now, return a generic description
        const descriptions = {
            '30232110-8': 'Echipamente de calcul și accesorii',
            '45000000-7': 'Lucrări de construcții',
            '03000000-1': 'Produse agricole, horticole și silviculturale',
            '15000000-8': 'Produse alimentare și băuturi',
            '18000000-9': 'Îmbrăcăminte, încălțăminte și articole din piele',
            '24000000-4': 'Produse chimice',
            '31000000-6': 'Echipamente și aparate electrice',
            '34000000-0': 'Echipamente de transport și piese auxiliare',
            '35000000-1': 'Echipamente de securitate, de luptă împotriva incendiilor și de poliție',
            '39000000-2': 'Mobilier și produse de mobilier',
            '50000000-5': 'Servicii de reparare și întreținere',
            '60000000-8': 'Servicii de transport',
            '72000000-5': 'Servicii IT: consultanță, dezvoltare software',
            '79000000-4': 'Servicii comerciale',
            '85000000-9': 'Servicii de sănătate și de asistență socială'
        };

        return descriptions[cpvCode] || `Cod CPV: ${cpvCode}`;
    }

    /**
     * Fetch user subscriptions from Firebase
     */
    async function fetchMySubscriptions() {
        if (!magentoUserId.value || !appUser.value) {
            error.value = 'Utilizator neautentificat';
            return;
        }

        loading.value = true;
        error.value = null;

        try {
            const db = getFirestore();
            const docRef = doc(db, 'subscriptions', magentoUserId.value);
            const docSnap = await getDoc(docRef);

            if (docSnap.exists()) {
                const userData = docSnap.data();
                subscriptions.value = userData.topics || [];

                // Update appUser if needed
                if (appUser.value) {
                    appUser.value.topics = userData.topics || [];
                }
            } else {
                subscriptions.value = [];
                error.value = 'Nu s-au găsit subscripții';
            }
        } catch (err) {
            error.value = err.message || 'Eroare la încărcarea subscripțiilor';
            console.error('Error fetching subscriptions:', err);
        } finally {
            loading.value = false;
        }
    }

    /**
     * Unsubscribe from a specific CPV code
     * @param {string} cpvCode - The CPV code to unsubscribe from
     */
    async function unsubscribeFromCPV(cpvCode) {
        if (!magentoUserId.value || !appUser.value) {
            toast.error('Utilizator neautentificat');
            return false;
        }

        try {
            const db = getFirestore();
            const docRef = doc(db, 'subscriptions', magentoUserId.value);

            // Remove CPV code from topics array
            const currentTopics = appUser.value.topics || [];
            const updatedTopics = currentTopics.filter(topic => topic !== cpvCode);

            // Update Firebase document
            await updateDoc(docRef, {
                topics: updatedTopics,
                updatedAt: Date.now()
            });

            // Update local appUser
            appUser.value.topics = updatedTopics;

            // Update local subscriptions
            subscriptions.value = updatedTopics;

            toast.success(`Te-ai dezabonat de la codul CPV: ${cpvCode}`);
            return true;
        } catch (err) {
            console.error('Error unsubscribing from CPV:', err);
            toast.error('Eroare la dezabonare');
            return false;
        }
    }

    /**
     * Subscribe to a specific CPV code
     * @param {string} cpvCode - The CPV code to subscribe to
     */
    async function subscribeToCPV(cpvCode) {
        if (!magentoUserId.value || !appUser.value) {
            toast.error('Utilizator neautentificat');
            return false;
        }

        try {
            const db = getFirestore();
            const docRef = doc(db, 'subscriptions', magentoUserId.value);

            // Add CPV code to topics array if not already present
            const currentTopics = appUser.value.topics || [];
            if (!currentTopics.includes(cpvCode)) {
                const updatedTopics = [...currentTopics, cpvCode];

                // Update Firebase document
                await updateDoc(docRef, {
                    topics: updatedTopics,
                    updatedAt: Date.now()
                });

                // Update local appUser
                appUser.value.topics = updatedTopics;

                // Update local subscriptions
                subscriptions.value = updatedTopics;

                toast.success(`Te-ai abonat la codul CPV: ${cpvCode}`);
                return true;
            } else {
                toast.info('Ești deja abonat la acest cod CPV');
                return false;
            }
        } catch (err) {
            console.error('Error subscribing to CPV:', err);
            toast.error('Eroare la abonare');
            return false;
        }
    }

    /**
     * Toggle subscription status for a CPV code
     * @param {string} cpvCode - The CPV code to toggle
     */
    async function toggleCPVSubscription(cpvCode) {
        if (!appUser.value?.topics) {
            return await subscribeToCPV(cpvCode);
        }

        const isCurrentlySubscribed = appUser.value.topics.includes(cpvCode);

        if (isCurrentlySubscribed) {
            return await unsubscribeFromCPV(cpvCode);
        } else {
            return await subscribeToCPV(cpvCode);
        }
    }

    /**
     * Check if user is subscribed to a specific CPV code
     * @param {string} cpvCode - The CPV code to check
     * @returns {boolean}
     */
    function isSubscribedToCPV(cpvCode) {
        return appUser.value?.topics?.includes(cpvCode) || false;
    }

    /**
     * Get the count of active subscriptions
     */
    const subscriptionCount = computed(() => {
        return appUser.value?.topics?.length || 0;
    });

    return {
        // State
        subscriptions,
        formattedSubscriptions,
        loading,
        error,
        subscriptionCount,

        // Methods
        fetchMySubscriptions,
        unsubscribeFromCPV,
        subscribeToCPV,
        toggleCPVSubscription,
        isSubscribedToCPV
    };
}
