import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { settingsAdminService } from '../services/settingsAdminService';
import { useNotification } from './reduxHooks';

/**
 * Hook for fetching all settings
 */
export const useAdminSettings = () => {
  return useQuery({
    queryKey: ['admin-settings'],
    queryFn: settingsAdminService.getAllSettings
  });
};

/**
 * Hook for fetching settings by category
 * @param {string} category - Category name
 */
export const useAdminSettingsByCategory = (category) => {
  return useQuery({
    queryKey: ['admin-settings', category],
    queryFn: () => settingsAdminService.getSettingsByCategory(category),
    enabled: !!category
  });
};

/**
 * Hook for fetching a single setting
 * @param {string} key - Setting key
 */
export const useAdminSetting = (key) => {
  return useQuery({
    queryKey: ['admin-setting', key],
    queryFn: () => settingsAdminService.getSetting(key),
    enabled: !!key
  });
};

/**
 * Hook for updating a single setting
 */
export const useUpdateSetting = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: ({ key, value, category }) => settingsAdminService.updateSetting(key, value, category),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-settings'] });
      notification.showNotification('Setting updated successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update setting',
        'error'
      );
    }
  });
};

/**
 * Hook for updating multiple settings at once
 */
export const useUpdateSettings = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: (settings) => settingsAdminService.updateSettings(settings),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-settings'] });
      notification.showNotification('Settings updated successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update settings',
        'error'
      );
    }
  });
};

/**
 * Hook for deleting a setting
 */
export const useDeleteSetting = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: (key) => settingsAdminService.deleteSetting(key),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-settings'] });
      notification.showNotification('Setting deleted successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to delete setting',
        'error'
      );
    }
  });
};