// API service for communicating with PHP backend
// Base configuration for API calls

const API_BASE_URL = process.env.REACT_APP_API_URL || '/api';

class ApiService {
  constructor() {
    this.baseURL = API_BASE_URL;
  }

  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
      ...options,
    };

    // Add auth token if available
    const token = localStorage.getItem('auth_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    try {
      const response = await fetch(url, config);
      
      // Handle different response types
      const contentType = response.headers.get('content-type');
      let data;
      
      if (contentType && contentType.includes('application/json')) {
        data = await response.json();
      } else {
        data = await response.text();
      }
      
      if (!response.ok) {
        // Handle authentication errors
        if (response.status === 401) {
          this.handleAuthError();
          throw new Error('Sesión expirada. Por favor, inicie sesión nuevamente.');
        }
        
        // Handle other errors
        const errorMessage = data?.error || data?.message || `HTTP error! status: ${response.status}`;
        throw new Error(errorMessage);
      }
      
      return data;
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  handleAuthError() {
    // Clear stored auth data
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user_data');
    
    // Redirect to login if not already there
    if (window.location.pathname !== '/login') {
      window.location.href = '/login';
    }
  }

  // Auth methods
  async login(credentials) {
    const response = await this.request('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    });
    
    // Store token and user data
    if (response.token) {
      localStorage.setItem('auth_token', response.token);
      localStorage.setItem('user_data', JSON.stringify(response.user));
    }
    
    return response;
  }

  async logout() {
    try {
      await this.request('/auth/logout', {
        method: 'POST',
      });
    } catch (error) {
      console.error('Logout request failed:', error);
    } finally {
      // Always clear local storage
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_data');
    }
  }

  async getCurrentUser() {
    return this.request('/auth/me');
  }

  async refreshToken() {
    return this.request('/auth/refresh', {
      method: 'POST',
    });
  }

  // User management methods (Admin only)
  async getUsers() {
    return this.request('/users');
  }

  async createUser(userData) {
    return this.request('/users', {
      method: 'POST',
      body: JSON.stringify(userData),
    });
  }

  async updateUser(userId, userData) {
    return this.request(`/users/${userId}`, {
      method: 'PUT',
      body: JSON.stringify(userData),
    });
  }

  async deleteUser(userId) {
    return this.request(`/users/${userId}`, {
      method: 'DELETE',
    });
  }

  // Projects methods
  async getProjects() {
    return this.request('/projects');
  }

  async getProject(projectId) {
    return this.request(`/projects/${projectId}`);
  }

  async createProject(projectData) {
    return this.request('/projects', {
      method: 'POST',
      body: JSON.stringify(projectData),
    });
  }

  async updateProject(projectId, projectData) {
    return this.request(`/projects/${projectId}`, {
      method: 'PUT',
      body: JSON.stringify(projectData),
    });
  }

  async deleteProject(projectId) {
    return this.request(`/projects/${projectId}`, {
      method: 'DELETE',
    });
  }

  // Document upload methods
  async uploadDocument(formData, onProgress) {
    const url = `${this.baseURL}/projects/documents`;
    
    // Add auth token
    const token = localStorage.getItem('auth_token');
    
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      // Set up progress tracking
      if (onProgress) {
        xhr.upload.addEventListener('progress', onProgress);
      }
      
      xhr.addEventListener('load', () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText);
            resolve(response);
          } catch (e) {
            resolve(xhr.responseText);
          }
        } else {
          try {
            const error = JSON.parse(xhr.responseText);
            reject(new Error(error.error || `HTTP error! status: ${xhr.status}`));
          } catch (e) {
            reject(new Error(`HTTP error! status: ${xhr.status}`));
          }
        }
      });
      
      xhr.addEventListener('error', () => {
        reject(new Error('Network error occurred'));
      });
      
      xhr.open('POST', url);
      
      if (token) {
        xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      }
      
      xhr.send(formData);
    });
  }

  async downloadDocument(projectId, documentPath) {
    const response = await fetch(`${this.baseURL}/projects/${projectId}/documents/${encodeURIComponent(documentPath)}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
      }
    });
    
    if (!response.ok) {
      throw new Error(`Error downloading document: ${response.status}`);
    }
    
    return response.blob();
  }

  // Rodales methods
  async getRodalesByProject(projectId) {
    return this.request(`/projects/${projectId}/rodales`);
  }

  async getRodal(rodalId) {
    return this.request(`/rodales/${rodalId}`);
  }

  async createRodal(projectId, rodalData) {
    return this.request(`/projects/${projectId}/rodales`, {
      method: 'POST',
      body: JSON.stringify(rodalData),
    });
  }

  async updateRodal(rodalId, rodalData) {
    return this.request(`/rodales/${rodalId}`, {
      method: 'PUT',
      body: JSON.stringify(rodalData),
    });
  }

  async deleteRodal(rodalId) {
    return this.request(`/rodales/${rodalId}`, {
      method: 'DELETE',
    });
  }

  async getRodalFieldData(rodalId, filters = {}) {
    const queryParams = new URLSearchParams(filters).toString();
    const endpoint = `/rodales/${rodalId}/field-data${queryParams ? `?${queryParams}` : ''}`;
    return this.request(endpoint);
  }

  async getRodalCalculations(rodalId) {
    return this.request(`/rodales/${rodalId}/calculations`);
  }

  async exportRodalCSV(rodalId) {
    return this.request(`/rodales/${rodalId}/export-csv`);
  }

  async getProjectSummary(projectId) {
    return this.request(`/projects/${projectId}/summary`);
  }

  async refreshCalculations(rodalId) {
    return this.request(`/calculations/refresh/${rodalId}`, {
      method: 'POST',
    });
  }

  // Field data methods
  async syncFieldData(data) {
    return this.request('/field-data/sync', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // Species methods
  async getSpecies() {
    return this.request('/species');
  }

  async getRecommendedSpecies() {
    return this.request('/species/recommended');
  }

  async searchSpecies(searchTerm) {
    return this.request(`/species/search?q=${encodeURIComponent(searchTerm)}`);
  }

  async getMostUsedSpecies(limit = 10) {
    return this.request(`/species/most-used?limit=${limit}`);
  }

  async getSpeciesStats() {
    return this.request('/species/stats');
  }

  async getSpeciesById(id) {
    return this.request(`/species/${id}`);
  }

  async createSpecies(speciesData) {
    return this.request('/species', {
      method: 'POST',
      body: JSON.stringify(speciesData),
    });
  }

  async initializeSpeciesCatalog() {
    return this.request('/species/initialize', {
      method: 'POST',
    });
  }

  // Generic HTTP methods for sync service
  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' });
  }

  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' });
  }

  // Utility methods
  isAuthenticated() {
    const token = localStorage.getItem('auth_token');
    const userData = localStorage.getItem('user_data');
    return !!(token && userData);
  }

  getCurrentUserData() {
    const userData = localStorage.getItem('user_data');
    return userData ? JSON.parse(userData) : null;
  }
}

export default new ApiService();