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

/**
 * Hook for fetching all email campaigns
 * @param {string} status - Optional filter by status
 */
export const useEmailCampaigns = (status) => {
  return useQuery({
    queryKey: ['email-campaigns', status],
    queryFn: async () => {
      const params = {};
      if (status) params.status = status;
      const response = await apiClient.get('/admin/email-campaigns', { params });
      return response.data;
    }
  });
};

/**
 * Hook for fetching a single email campaign
 * @param {string} id - Campaign ID
 */
export const useEmailCampaign = (id) => {
  return useQuery({
    queryKey: ['email-campaign', id],
    queryFn: async () => {
      const response = await apiClient.get(`/admin/email-campaigns/${id}`);
      return response.data;
    },
    enabled: !!id
  });
};

/**
 * Hook for creating a new email campaign
 */
export const useCreateEmailCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (campaignData) => {
      const response = await apiClient.post('/admin/email-campaigns', campaignData);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      notification.showNotification('Campaign created successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to create campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for updating an existing email campaign
 */
export const useUpdateEmailCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ id, campaignData }) => {
      const response = await apiClient.put(`/admin/email-campaigns/${id}`, campaignData);
      return response.data;
    },
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      queryClient.invalidateQueries({ queryKey: ['email-campaign', variables.id] });
      notification.showNotification('Campaign updated successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for deleting an email campaign
 */
export const useDeleteEmailCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.delete(`/admin/email-campaigns/${id}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      notification.showNotification('Campaign deleted successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to delete campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for duplicating an email campaign
 */
export const useDuplicateEmailCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.post(`/admin/email-campaigns/${id}/duplicate`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      notification.showNotification('Campaign duplicated successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to duplicate campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for sending an email campaign
 */
export const useSendCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.post(`/admin/email-campaigns/${id}/send`);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      queryClient.invalidateQueries({ queryKey: ['email-campaign', data.id] });
      notification.showNotification('Campaign sent successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to send campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for scheduling an email campaign
 */
export const useScheduleCampaign = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ campaignId, scheduledDate }) => {
      const response = await apiClient.post(`/admin/email-campaigns/${campaignId}/schedule`, {
        scheduledDate
      });
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['email-campaigns'] });
      queryClient.invalidateQueries({ queryKey: ['email-campaign', data.id] });
      notification.showNotification('Campaign scheduled successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to schedule campaign',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for sending a preview/test email
 */
export const usePreviewCampaign = () => {
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ campaignId, email }) => {
      const response = await apiClient.post(`/admin/email-campaigns/${campaignId}/preview`, {
        email
      });
      return response.data;
    },
    onSuccess: () => {
      notification.showNotification('Test email sent successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to send test email',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for fetching campaign analytics
 */
export const useCampaignAnalytics = (campaignId) => {
  return useQuery({
    queryKey: ['campaign-analytics', campaignId],
    queryFn: async () => {
      const response = await apiClient.get(`/admin/email-campaigns/${campaignId}/analytics`);
      return response.data;
    },
    enabled: !!campaignId
  });
};

/**
 * Hook for fetching campaign subscriber activity
 */
export const useCampaignSubscriberActivity = (
  campaignId, 
  page = 0, 
  pageSize = 25, 
  searchTerm = '', 
  activityType = 'all',
  tabValue
) => {
  return useQuery({
    queryKey: ['campaign-activity', campaignId, page, pageSize, searchTerm, activityType],
    queryFn: async () => {
      const params = { 
        page, 
        pageSize,
        search: searchTerm, 
        type: activityType === 'all' ? undefined : activityType 
      };
      
      const response = await apiClient.get(
        `/admin/email-campaigns/${campaignId}/activity`, 
        { params }
      );
      return response.data;
    },
    enabled: !!campaignId && tabValue === 2
  });
};

/**
 * Hook for exporting campaign report
 */
export const useExportCampaignReport = () => {
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (campaignId) => {
      const response = await apiClient.get(`/admin/email-campaigns/${campaignId}/export`, {
        responseType: 'blob'
      });
      
      // Create a download link and trigger the download
      const blob = new Blob([response.data], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `campaign-report-${campaignId}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
      
      return true;
    },
    onSuccess: () => {
      notification.showNotification('Report exported successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to export report',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for fetching all mailing lists
 */
export const useMailingLists = () => {
  return useQuery({
    queryKey: ['mailing-lists'],
    queryFn: async () => {
      const response = await apiClient.get('/admin/mailing-lists');
      return response.data;
    }
  });
};

/**
 * Hook for fetching a single mailing list
 */
export const useMailingList = (listId) => {
  return useQuery({
    queryKey: ['mailing-list', listId],
    queryFn: async () => {
      const response = await apiClient.get(`/admin/mailing-lists/${listId}`);
      return response.data;
    },
    enabled: !!listId
  });
};

/**
 * Hook for creating a new mailing list
 */
export const useCreateMailingList = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (listData) => {
      const response = await apiClient.post('/admin/mailing-lists', listData);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['mailing-lists'] });
      notification.showNotification('Mailing list created successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to create mailing list',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for updating a mailing list
 */
export const useUpdateMailingList = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ id, listData }) => {
      const response = await apiClient.put(`/admin/mailing-lists/${id}`, listData);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['mailing-lists'] });
      queryClient.invalidateQueries({ queryKey: ['mailing-list', data.id] });
      notification.showNotification('Mailing list updated successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update mailing list',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for deleting a mailing list
 */
export const useDeleteMailingList = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.delete(`/admin/mailing-lists/${id}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mailing-lists'] });
      notification.showNotification('Mailing list deleted successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to delete mailing list',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for importing subscribers to a list
 */
export const useImportSubscribers = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (formData) => {
      const response = await apiClient.post('/admin/mailing-lists/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['mailing-lists'] });
      queryClient.invalidateQueries({ queryKey: ['mailing-list', data.listId] });
      queryClient.invalidateQueries({ queryKey: ['subscribers', data.listId] });
      notification.showNotification(`${data.importedCount} subscribers imported successfully`, 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to import subscribers',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for exporting subscribers from a list
 */
export const useExportSubscribers = () => {
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (listId) => {
      const response = await apiClient.get(`/admin/mailing-lists/${listId}/export`, {
        responseType: 'blob'
      });
      
      // Create a download link and trigger the download
      const blob = new Blob([response.data], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `subscribers-${listId}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
      
      return true;
    },
    onSuccess: () => {
      notification.showNotification('Subscribers exported successfully', 'success');
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to export subscribers',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for fetching list subscribers
 */
export const useSubscribers = (
  listId, 
  page = 0, 
  pageSize = 25, 
  searchTerm = '', 
  status = 'all'
) => {
  return useQuery({
    queryKey: ['subscribers', listId, page, pageSize, searchTerm, status],
    queryFn: async () => {
      const params = { 
        page, 
        pageSize, 
        search: searchTerm, 
        status: status === 'all' ? undefined : status 
      };
      
      const response = await apiClient.get(
        `/admin/mailing-lists/${listId}/subscribers`, 
        { params }
      );
      return response.data;
    },
    enabled: !!listId
  });
};

/**
 * Hook for adding a subscriber to a list
 */
export const useAddSubscriber = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ listId, subscriberData }) => {
      const response = await apiClient.post(`/admin/mailing-lists/${listId}/subscribers`, subscriberData);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['subscribers', data.listId] });
      queryClient.invalidateQueries({ queryKey: ['mailing-list', data.listId] });
      notification.showNotification('Subscriber added successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to add subscriber',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for updating a subscriber
 */
export const useUpdateSubscriber = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async ({ id, subscriberData }) => {
      const response = await apiClient.put(`/admin/subscribers/${id}`, subscriberData);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['subscribers'] });
      queryClient.invalidateQueries({ queryKey: ['subscriber', data.id] });
      notification.showNotification('Subscriber updated successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to update subscriber',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for deleting a subscriber
 */
export const useDeleteSubscriber = () => {
  const queryClient = useQueryClient();
  const notification = useNotification();
  
  return useMutation({
    mutationFn: async (id) => {
      const response = await apiClient.delete(`/admin/subscribers/${id}`);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['subscribers'] });
      notification.showNotification('Subscriber deleted successfully', 'success');
      return data;
    },
    onError: (error) => {
      notification.showNotification(
        error.message || 'Failed to delete subscriber',
        'error'
      );
      throw error;
    }
  });
};

/**
 * Hook for fetching subscriber activity
 */
export const useSubscriberActivity = (subscriberId, enabled = false) => {
  return useQuery({
    queryKey: ['subscriber-activity', subscriberId],
    queryFn: async () => {
      const response = await apiClient.get(`/admin/subscribers/${subscriberId}/activity`);
      return response.data;
    },
    enabled: !!subscriberId && enabled
  });
};

export default {
  useEmailCampaigns,
  useEmailCampaign,
  useCreateEmailCampaign,
  useUpdateEmailCampaign,
  useDeleteEmailCampaign,
  useDuplicateEmailCampaign,
  useSendCampaign,
  useScheduleCampaign,
  usePreviewCampaign,
  useCampaignAnalytics,
  useCampaignSubscriberActivity,
  useExportCampaignReport,
  useMailingLists,
  useMailingList,
  useCreateMailingList,
  useUpdateMailingList,
  useDeleteMailingList,
  useImportSubscribers,
  useExportSubscribers,
  useSubscribers,
  useAddSubscriber,
  useUpdateSubscriber,
  useDeleteSubscriber,
  useSubscriberActivity
};