// NEW FILE - hooks/useUserRewardSettings.js
import { useState, useCallback } from 'react';
import axios from 'axios';

export const useUserRewardSettings = (formData) => {
    const [userCustomSettings, setUserCustomSettings] = useState({});
    const [hasCustomSettings, setHasCustomSettings] = useState(false);
    const [globalSettings, setGlobalSettings] = useState({});
    const [settingsLoading, setSettingsLoading] = useState(false);

    const fetchUserCustomSettings = useCallback(async (userId) => {
        if (!userId) return null;
        
        try {
            const requestData = new FormData();
            requestData.append('action', 'ecre_fetch_user_reward_settings');
            requestData.append('nonce', ecreAdmin.nonce);
            requestData.append('user_id', userId);

            const response = await axios.post(ecreAdmin.ajaxurl, requestData);
            
            if (response.data.success) {
                const { merged_settings, custom_settings, has_custom_settings } = response.data.data;
                
                setGlobalSettings(merged_settings);
                setUserCustomSettings(custom_settings);
                setHasCustomSettings(has_custom_settings);
                
                return {
                    merged_settings,
                    custom_settings,
                    has_custom_settings,
                    // Helper method to get effective value with fallback
                    getEffectiveValue: (key, defaultValue = null) => {
                        return custom_settings.hasOwnProperty(key) 
                            ? custom_settings[key] 
                            : (merged_settings[key] || formData[key] || defaultValue);
                    }
                };
            }
        } catch (error) {
            console.error('Error fetching user settings:', error);
        }
        return null;
    }, [formData]);

    const saveUserCustomSettings = useCallback(async (userId, settings) => {
        if (!userId) return false;
        
        setSettingsLoading(true);
        try {
            const settingsData = new FormData();
            settingsData.append('action', 'ecre_save_user_reward_settings');
            settingsData.append('nonce', ecreAdmin.nonce);
            settingsData.append('user_id', userId);

            // FIX: Use JSON.stringify like your global settings
            settingsData.append('settings', JSON.stringify(settings));

            const response = await axios.post(ecreAdmin.ajaxurl, settingsData);
            
            if (response.data.success) {
                setHasCustomSettings(true);
                // Refresh settings after save
                await fetchUserCustomSettings(userId);
                return { success: true, data: response.data.data };
            } else {
                console.error('Failed to save settings:', response.data.data);
                return { success: false, error: response.data.data };
            }
        } catch (error) {
            console.error('Error saving settings:', error);
            return { success: false, error: error.message };
        } finally {
            setSettingsLoading(false);
        }
    }, [fetchUserCustomSettings]);

    const resetToDefaultSettings = useCallback(async (userId, settingKey = null) => {
        if (!userId) return false;
        
        setSettingsLoading(true);
        try {
            const resetData = new FormData();
            resetData.append('action', 'ecre_reset_user_reward_settings');
            resetData.append('nonce', ecreAdmin.nonce);
            resetData.append('user_id', userId);
            
            if (settingKey) {
                resetData.append('setting_key', settingKey);
            }

            const response = await axios.post(ecreAdmin.ajaxurl, resetData);
            
            if (response.data.success) {
                const { has_custom_settings } = response.data.data;
                setHasCustomSettings(has_custom_settings || false);
                
                if (!has_custom_settings) {
                    setUserCustomSettings({});
                }
                
                // Refresh settings after reset
                await fetchUserCustomSettings(userId);
                return { success: true, data: response.data.data };
            } else {
                console.error('Failed to reset settings:', response.data.data);
                return { success: false, error: response.data.data };
            }
        } catch (error) {
            console.error('Error resetting settings:', error);
            return { success: false, error: error.message };
        } finally {
            setSettingsLoading(false);
        }
    }, [fetchUserCustomSettings]);

    return {
        userCustomSettings,
        hasCustomSettings,
        globalSettings,
        settingsLoading,
        fetchUserCustomSettings,
        saveUserCustomSettings,
        resetToDefaultSettings
    };
};