import { ref, onMounted } from 'vue';
import axios from 'axios';

export function useUserAdditionalDetails() {
    const details = ref({
        settings: {},
        details: {}
    });
    const isLoading = ref(false);
    const joinedCooperatives = ref([]);

    const fetchUserDetails = async () => {
        isLoading.value = true;
        try {
            const response = await axios.post('/UserAdditionalDetails/Get');
            if (response.data.success) {
                details.value = response.data.data;
            }
        } catch (error) {
            console.error('Failed to fetch user additional details:', error);
        } finally {
            isLoading.value = false;
        }
    };

    const joinCooperative = async (cooperativeHash) => {
        isLoading.value = true;
        try {
            const response = await axios.post('/UserAdditionalDetails/UpdateCooperatives', {
                cooperative_hash: cooperativeHash,
                action: 'add'
            });
            if (response.data.success) {
                // If it was successful, update the local settings to reflect it
                if (!details.value.settings.cooperatives) {
                    details.value.settings.cooperatives = [];
                }
                if (!details.value.settings.cooperatives.includes(cooperativeHash)) {
                    details.value.settings.cooperatives.push(cooperativeHash);
                }
                return true;
            }
        } catch (error) {
            console.error('Failed to join cooperative:', error);
        } finally {
            isLoading.value = false;
        }
        return false;
    };

    const leaveCooperative = async (cooperativeHash) => {
        isLoading.value = true;
        try {
            const response = await axios.post('/UserAdditionalDetails/UpdateCooperatives', {
                cooperative_hash: cooperativeHash,
                action: 'remove'
            });
            if (response.data.success) {
                if (details.value.settings.cooperatives) {
                    details.value.settings.cooperatives = details.value.settings.cooperatives.filter(h => h !== cooperativeHash);
                }
                return true;
            }
        } catch (error) {
            console.error('Failed to leave cooperative:', error);
        } finally {
            isLoading.value = false;
        }
        return false;
    };

    const fetchJoinedCooperatives = async (userHash = null) => {
        isLoading.value = true;
        try {
            const response = await axios.post('/UserAdditionalDetails/GetCooperatives', {
                user_hash: userHash
            });
            if (response.data.success) {
                joinedCooperatives.value = response.data.data;
                return joinedCooperatives.value;
            }
        } catch (error) {
            console.error('Failed to fetch user cooperatives:', error);
        } finally {
            isLoading.value = false;
        }
        return [];
    };

    const searchUsersByCooperative = async (cooperativeHash) => {
        isLoading.value = true;
        try {
            const response = await axios.post('/UserAdditionalDetails/SearchByCooperative', {
                cooperative_hash: cooperativeHash
            });
            if (response.data.success) {
                return response.data.data;
            }
        } catch (error) {
            console.error('Failed to search users by cooperative:', error);
        } finally {
            isLoading.value = false;
        }
        return [];
    };

    const getJoinedCooperativeHashes = () => {
        return details.value.settings.cooperatives || [];
    };

    const hasJoinedCooperative = (cooperativeHash) => {
        return getJoinedCooperativeHashes().includes(cooperativeHash);
    };

    onMounted(() => {
        fetchUserDetails();
    });

    return {
        details,
        isLoading,
        joinedCooperatives,
        fetchUserDetails,
        joinCooperative,
        leaveCooperative,
        fetchJoinedCooperatives,
        searchUsersByCooperative,
        getJoinedCooperativeHashes,
        hasJoinedCooperative
    };
}
