import apiGlobal from '@/services/apiGlobal';
import { Volunteer, VolunteerTableParams } from '@/types/volunteer';

export const getAllVolunteers = async (params: VolunteerTableParams) => {
  try {
    // Build query parameters with filtering support
    const queryParams: any = {
      skip: params.offset,
      limit: params.limit,
    };

    // Add search filter if provided
    if (params.search && params.search.trim() !== '') {
      queryParams.search = params.search.trim();
    }

    // Add sorting parameters if provided
    if (params.sort) {
      queryParams.sort = params.sort;
    }
    if (params.sortField) {
      queryParams.sortField = params.sortField;
    }

    // Add filters if provided
    if (params.filters) {
      // Status filter
      if (params.filters.status && params.filters.status !== 'all') {
        queryParams.status = params.filters.status;
      }

      // Date range filter
      if (params.filters.dateFrom) {
        queryParams.fromDate = params.filters.dateFrom;
      }
      if (params.filters.dateTo) {
        queryParams.toDate = params.filters.dateTo;
      }

    }

    console.log('API call params:', queryParams);

    const response = await apiGlobal.get('/fetchAllVolunteerForm', {
      params: queryParams,
    });

    return {
      data: {
        data: {
          volunteers: response.data.data || [],
          count: response.data.totalCount || response.data.data?.length || 0,
          totalPages: response.data.totalPages || Math.ceil((response.data.totalCount || 0) / params.limit)
        }
      }
    };
  } catch (error) {
    console.error('Error fetching volunteers:', error);
    throw error;
  }
};

export const changeVolunteerStatus = async (formId: string, status: 'accepted' | 'rejected' | 'deleted') => {
  try {
    const payload: any = {
      formId,
      status,
    };
    
    // If status is deleted, also set the deleted flag
    if (status === 'deleted') {
      payload.deleted = true;
    }
    
    console.log('Changing volunteer status:', { formId, status, payload });
    
    const response = await apiGlobal.put('/changeVolunteerFormStatus', payload);
    
    console.log('Status change response:', response.data);
    
    return response.data;
  } catch (error) {
    console.error('Error changing volunteer status:', error);
    throw error;
  }
};


export const getVolunteerById = async (id: string) => {
  try {
    const response = await apiGlobal.get('/fetchVolunteerForms');
    
    // Find the volunteer by ID from the response
    const volunteers = response.data.data || [];
    const volunteer = volunteers.find((v: Volunteer) => v._id === id);
    
    if (!volunteer) {
      throw new Error('Volunteer not found');
    }
    
    return {
      data: {
        data: volunteer
      }
    };
  } catch (error) {
    console.error('Error fetching volunteer by ID:', error);
    throw error;
  }
};

export const exportVolunteersToCSV = (volunteers: Volunteer[]) => {
  const headers = [
    'Name',
    'Email',
    'Phone',
    'Address',
    'Preferred Contact',
    'Signup Date',
    'Status',
    'Skills',
    'Interests',
    'How They Heard',
    'Email Subscription',
    'Phone Subscription',
  ];

  const csvData = volunteers.map(volunteer => [
    volunteer.name || '',
    volunteer.formData.emailAddress || '',
    volunteer.formData.phoneNumber || '',
    volunteer.formData.address || '',
    volunteer.formData.preferedMethodOfcontact || '',
    volunteer.signupDate || '',
    volunteer.status || '',
    volunteer.formData.goodAt || '',
    volunteer.formData.interest.join('; ') || '',
    volunteer.formData.hearFrom || '',
    volunteer.formData.isEmailSubscribed ? 'Yes' : 'No',
    volunteer.formData.isPhoneSubscribed ? 'Yes' : 'No',
  ]);

  const csvContent = [
    headers.join(','),
    ...csvData.map(row => row.map(field => `"${field}"`).join(','))
  ].join('\n');

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `volunteers_${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// Get volunteer statistics
export const getVolunteerStats = async () => {
  try {
    const response = await apiGlobal.get('/volunteerStats');
    return response.data;
  } catch (error) {
    console.error('Error fetching volunteer stats:', error);
    throw error;
  }
};

// Bulk update volunteer status
export const bulkUpdateVolunteerStatus = async (volunteerIds: string[], status: 'accepted' | 'rejected') => {
  try {
    const response = await apiGlobal.put('/bulkUpdateVolunteerStatus', {
      volunteerIds,
      status,
    });
    return response.data;
  } catch (error) {
    console.error('Error bulk updating volunteer status:', error);
    throw error;
  }
};

// Send notification to volunteer
export const sendVolunteerNotification = async (volunteerId: string, message: string, type: 'email' | 'sms') => {
  try {
    const response = await apiGlobal.post('/sendVolunteerNotification', {
      volunteerId,
      message,
      type,
    });
    return response.data;
  } catch (error) {
    console.error('Error sending volunteer notification:', error);
    throw error;
  }
};
