import axios from 'axios';

class ApiService {
  constructor() {
    this.wpData = window.fluentcData || {};
    
    // Create axios instance for WordPress API calls
    this.wpApi = axios.create({
      baseURL: this.wpData.ajaxUrl || '/wp-admin/admin-ajax.php',
      timeout: 10000,
    });

    // Create axios instance for FluentC AI Agent API
    this.fluentcApi = axios.create({
      baseURL: 'https://dashboard.fluentc.io/',
      timeout: 30000, // Longer timeout for AI processing
      headers: {
        'Content-Type': 'application/json',
        // Authorization header will be added per request
      },
    });

    // Create axios instance for FluentC GraphQL API
    this.fluentcGraphQL = axios.create({
      baseURL: 'https://dashboard.fluentc.ai/graphql',
      timeout: 30000, // Longer timeout for AI processing
      headers: {
        'Content-Type': 'application/json',
        // Authorization header will be added per request
      },
    });

    // Add request interceptor for WordPress API
    this.wpApi.interceptors.request.use((config) => {
      // Add nonce for security - but only if data is not already FormData
      if (this.wpData.nonce) {
        if (config.data instanceof FormData) {
          // If it's FormData, append the nonce if it doesn't already exist
          if (!config.data.has('nonce')) {
            config.data.append('nonce', this.wpData.nonce);
          }
        } else {
          // For regular objects, spread the data
          config.data = {
            ...config.data,
            nonce: this.wpData.nonce,
          };
        }
      }
      return config;
    });

    // Add response interceptor for error handling
    this.wpApi.interceptors.response.use(
      (response) => response,
      (error) => {
        console.error('WordPress API Error:', error);
        return Promise.reject(error);
      }
    );

    // Add response interceptor for FluentC API
    this.fluentcApi.interceptors.response.use(
      (response) => response,
      (error) => {
        console.error('FluentC AI Agent API Error:', error);
        return Promise.reject(error);
      }
    );

    // Add response interceptor for FluentC GraphQL API
    this.fluentcGraphQL.interceptors.response.use(
      (response) => response,
      (error) => {
        console.error('FluentC GraphQL API Error:', error);
        return Promise.reject(error);
      }
    );
  }

  /**
   * Set FluentC API key for authentication
   * Note: API key is now handled server-side with a hardcoded key for the free plugin
   */
  setApiKey(apiKey) {
    // API key is now handled server-side with a hardcoded key
    // No configuration needed for the free plugin
    console.log('API key is handled server-side with hardcoded key for FluentC Free plugin');
  }

  /**
   * Test connection to WordPress API
   */
  async testConnection() {
    try {
      const formData = new FormData();
      formData.append('action', 'fluentc_api_call');
      formData.append('nonce', this.wpData.nonce);
      formData.append('test_data', JSON.stringify({ message: 'Hello from React!' }));

      const response = await this.wpApi.post('', formData);
      
      if (response.data.success) {
        return {
          success: true,
          message: 'Successfully connected to WordPress API!',
          data: response.data,
        };
      } else {
        throw new Error('API test failed');
      }
    } catch (error) {
      throw new Error(`Connection failed: ${error.message}`);
    }
  }

  /**
   * Translate text or HTML content using FluentC AI Agent
   */
  async translateContent(params = {}) {
    try {
      const { 
        input, 
        inputFormat = 'text', 
        targetLanguage, 
        sourceLanguage, 
        mode = 'real-time' 
      } = params;
      
      if (!input || !targetLanguage) {
        throw new Error('Input text and target language are required');
      }

      // Use WordPress AJAX to handle translation server-side (avoids CORS)
      const response = await this.makeWpAjaxCall('fluentc_translate_content', {
        input: input,
        input_format: inputFormat,
        target_language: targetLanguage,
        source_language: sourceLanguage,
        mode: mode
      });

      if (!response.success) {
        throw new Error(response.data || 'Translation failed');
      }

      if (mode === 'real-time') {
        return {
          success: true,
          status: response.data.status,
          translation: response.data.translation,
          tokenCount: response.data.tokenCount,
          sourceLanguageDetected: response.data.sourceLanguageDetected
        };
      } else {
        // Batch mode returns job_id
        return {
          success: true,
          jobId: response.data.jobId
        };
      }
    } catch (error) {
      console.error('Error translating content:', error);
      throw new Error(`Translation failed: ${error.message}`);
    }
  }

  /**
   * Get translation results for batch jobs
   */
  async getTranslationResults(jobId) {
    try {
      if (!jobId) {
        throw new Error('Job ID is required');
      }

      // Use WordPress AJAX to get translation results server-side (avoids CORS)
      const response = await this.makeWpAjaxCall('fluentc_get_translation_results', {
        job_id: jobId
      });
      
      if (!response.success) {
        throw new Error(response.data || 'Failed to get translation results');
      }
      
      return {
        success: true,
        status: response.data.status,
        translation: response.data.translation,
        tokenCount: response.data.tokenCount,
        sourceLanguageDetected: response.data.sourceLanguageDetected,
        estimatedWaitSeconds: response.data.estimatedWaitSeconds,
        nextPollAfter: response.data.nextPollAfter,
        error: response.data.error
      };
    } catch (error) {
      console.error('Error getting translation results:', error);
      throw new Error(`Failed to get translation results: ${error.message}`);
    }
  }

  /**
   * Detect language of content using FluentC AI Agent
   */
  async detectLanguage(params = {}) {
    try {
      const { input, inputFormat = 'text' } = params;
      
      if (!input) {
        throw new Error('Input content is required');
      }

      // API key is handled server-side, no need to check here
      const response = await this.fluentcApi.post('ai_agent/checklanguage', {
        input: input,
        input_format: inputFormat
      });

      return {
        success: true,
        message: response.data.message
      };
    } catch (error) {
      console.error('Error detecting language:', error);
      const errorMessage = error.response?.data?.error || error.message;
      throw new Error(`Language detection failed: ${errorMessage}`);
    }
  }

  /**
   * Get sitemap from WordPress
   */
  async getSitemap() {
    try {
      const response = await this.makeWpAjaxCall('fluentc_get_sitemap');
      if (response.success) {
        return {
          success: true,
          urls: response.data.urls,
          message: response.data.message
        };
      } else {
        throw new Error(response.data || 'A valid sitemap was not found.');
      }
    } catch (error) {
      console.error('Error getting sitemap:', error);
      throw new Error(`Failed to retrieve sitemap: ${error.message}`);
    }
  }

  /**
   * Validate pages
   */
  async validatePages(params = {}) {
    try {
      const { pageUrls } = params;
      const response = await this.makeWpAjaxCall('fluentc_validate_pages', {
        page_urls: pageUrls
      });

      if (response.success) {
        return {
          success: true,
          results: response.data,
        };
      } else {
        throw new Error(response.data || 'An unknown error occurred during page validation.');
      }
    } catch (error) {
      console.error('Error validating pages:', error);
      throw new Error(`Page validation failed: ${error.message}`);
    }
  }

  /**
   * Get latest batch status
   */
  async getLatestBatchStatus(params = {}) {
    try {
      const { site_id } = params;
      const data = {};
      if (site_id) {
        data.site_id = site_id;
      }
      const response = await this.makeWpAjaxCall('fluentc_get_latest_batch_status', data);
      return response;
    } catch (error) {
      console.error('Error getting latest batch status:', error);
      throw new Error(`Failed to get latest batch status: ${error.message}`);
    }
  }

  /**
   * Get available languages from FluentC AI Agent
   */
  async getAvailableLanguages() {
    try {
      // Use WordPress AJAX to get languages server-side (avoids CORS)
      const response = await this.makeWpAjaxCall('fluentc_get_language_options');
      
      if (!response.success) {
        throw new Error(response.data || 'Failed to get available languages');
      }
      
      return {
        success: true,
        supportedLanguages: response.data.targetLanguages,
        sourceLanguages: response.data.sourceLanguages
      };
    } catch (error) {
      console.error('Error fetching available languages:', error);
      throw new Error(`Failed to get available languages: ${error.message}`);
    }
  }

  /**
   * Translate page content using FluentC AI Agent
   */
  async translatePage(params = {}) {
    try {
      const { pageUrl, targetLanguage, sourceLanguage, mode = 'batch' } = params;
      
      if (!pageUrl || !targetLanguage) {
        throw new Error('Page URL and target language are required');
      }

      // Note: In a real implementation, you would need to fetch the page content
      // from the server side to avoid CORS issues. For now, we'll treat pageUrl as content.
      return await this.translateContent({
        input: pageUrl,
        inputFormat: 'html',
        targetLanguage: targetLanguage,
        sourceLanguage: sourceLanguage,
        mode: mode
      });
    } catch (error) {
      console.error('Error translating page:', error);
      throw new Error(`Page translation failed: ${error.message}`);
    }
  }

  /**
   * Make custom WordPress AJAX call
   */
  async makeWpAjaxCall(action, data = {}) {
    try {
      const formData = new FormData();
      formData.append('action', action);
      formData.append('nonce', this.wpData.nonce);
      
      // Append all data fields
      Object.keys(data).forEach(key => {
        formData.append(key, typeof data[key] === 'object' ? JSON.stringify(data[key]) : data[key]);
      });

      // Debug logging
      console.log('WordPress AJAX Call:', {
        action,
        dataKeys: Object.keys(data),
        formDataEntries: Array.from(formData.entries())
      });

      const response = await this.wpApi.post('', formData);
      return response.data;
    } catch (error) {
      console.error('WordPress AJAX Error:', error);
      console.error('Error details:', {
        status: error.response?.status,
        statusText: error.response?.statusText,
        data: error.response?.data
      });
      throw error;
    }
  }

  /**
   * Make external API call
   */
  async makeExternalCall(url, options = {}) {
    try {
      const response = await this.fluentcApi({
        url,
        ...options,
      });
      return response.data;
    } catch (error) {
      console.error('External API Error:', error);
      throw error;
    }
  }

  /**
   * Process HTML content using FluentC GraphQL API
   */
  async processHtml(params = {}) {
    try {
      const { 
        html, 
        base64Encode = true, 
        sourceLanguage = 'en' 
      } = params;
      
      if (!html) {
        throw new Error('HTML content is required');
      }

      // Use WordPress AJAX to process HTML server-side (avoids CORS)
      const response = await this.makeWpAjaxCall('fluentc_process_html', {
        html: html,
        base64_encode: base64Encode,
        source_language: sourceLanguage
      });

      if (!response.success) {
        throw new Error(response.data || 'HTML processing failed');
      }
      
      return {
        success: true,
        count: response.data.count,
        processedAt: response.data.processedAt,
        textNodes: response.data.textNodes
      };
    } catch (error) {
      console.error('Error processing HTML:', error);
      throw new Error(`HTML processing failed: ${error.message}`);
    }
  }

  /**
   * Fetch HTML content from a URL
   * @param {string} pageUrl - The URL to fetch
   * @param {boolean} allowExternal - Whether to allow external URLs (for shortcode usage)
   */
  async fetchPageHtml(pageUrl, allowExternal = false) {
    try {
      if (!pageUrl) {
        throw new Error('Page URL is required');
      }

      // Use WordPress AJAX to fetch HTML server-side (handles CORS and security)
      const response = await this.makeWpAjaxCall('fluentc_fetch_page_html', {
        page_url: pageUrl,
        allow_external: allowExternal ? 'true' : 'false'
      });

      if (!response.success) {
        throw new Error(response.data || 'Failed to fetch page HTML');
      }

      return {
        success: true,
        html: response.data.html,
        url: response.data.url,
        size: response.data.size,
        fetchedAt: response.data.fetched_at
      };
    } catch (error) {
      console.error('Error fetching page HTML:', error);
      throw new Error(`HTML fetch failed: ${error.message}`);
    }
  }

}

export default new ApiService(); 