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

// ========== USER HOOKS ==========

/**
 * Hook for sending an email to a user
 */
export const useSendEmail = () => {
    const queryClient = useQueryClient();
    const notification = useNotification();
    
    return useMutation({
      mutationFn: (emailData) => adminUserService.sendEmail(emailData),
      onSuccess: () => {
        notification.showNotification('Email sent successfully', 'success');
      },
      onError: (error) => {
        notification.showNotification(
          error.message || 'Failed to send email',
          'error'
        );
      }
    });
  };


/**
 * Hook for fetching all users (admin only)
 */
export const useAdminUsers = () => {
  return useQuery({
    queryKey: ['admin-users'],
    queryFn: adminUserService.getAllUsers
  });
};

/**
 * Hook for fetching a single user by ID (admin only)
 * @param {string} id - User ID
 */
export const useAdminUser = (id) => {
  return useQuery({
    queryKey: ['admin-user', id],
    queryFn: () => adminUserService.getUserById(id),
    enabled: !!id
  });
};

/**
 * Hook for updating a user (admin only)
 */
export const useUpdateUser = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();

  return useMutation({
    mutationFn: ({ id, data }) => adminUserService.updateUser(id, data),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      queryClient.invalidateQueries({ queryKey: ['admin-user', data.user.id] });
      notification.showNotification('User updated successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update user',
        'error'
      );
    }
  });
};

// ========== ORDER HOOKS ==========

/**
 * Hook for fetching all orders (admin only)
 */
export const useAdminOrders = () => {
  return useQuery({
    queryKey: ['admin-orders'],
    queryFn: adminOrderService.getAllOrders
  });
};

/**
 * Hook for fetching a single order by ID (admin only)
 * @param {string} id - Order ID
 * @param {Object} options - Additional options
 */
export const useAdminOrder = (id, options = {}) => {
  return useQuery({
    queryKey: ['admin-order', id],
    queryFn: () => adminOrderService.getOrderById(id),
    enabled: !!id && (options.enabled !== undefined ? options.enabled : true)
  });
};

/**
 * Hook for updating an order status (admin only)
 */
export const useUpdateOrderStatus = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();

  return useMutation({
    mutationFn: ({ orderId, status, shippingData, sendNotification }) => {
      // If shipping data is provided, include it in the request
      if (shippingData && sendNotification) {
        return adminOrderService.updateOrderStatusWithShipping(
          orderId, 
          status, 
          shippingData, 
          sendNotification
        );
      }
      // Otherwise just update the status
      return adminOrderService.updateOrderStatus(orderId, status);
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['admin-orders'] });
      queryClient.invalidateQueries({ queryKey: ['admin-order', data.order.id] });
      notification.showNotification('Order status updated successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update order status',
        'error'
      );
    }
  });
};