import axios from 'axios';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://translynx.ai/api';
const API_TIMEOUT = parseInt(process.env.NEXT_PUBLIC_API_TIMEOUT || '30000');

// Create axios instance
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: API_TIMEOUT,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor to add auth token
apiClient.interceptors.request.use(
  (config) => {
    // Don't add auth token for login/signup/public endpoints
    const publicEndpoints = ['/auth/login', '/auth/signup', '/auth/forgot-password', '/auth/reset-password', '/settings', '/languages', '/health'];
    const isPublicEndpoint = publicEndpoints.some(endpoint => config.url?.includes(endpoint));

    if (!isPublicEndpoint) {
      const token = localStorage.getItem('auth_token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Custom error class for API errors
export class ApiError extends Error {
  status: number;
  code?: string;

  constructor(message: string, status: number, code?: string) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
    this.code = code;
  }
}

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    // Handle network errors
    if (!error.response) {
      throw new ApiError(
        'Network error. Please check your internet connection.',
        0,
        'NETWORK_ERROR'
      );
    }

    const status = error.response.status;
    const data = error.response.data;
    const requestUrl = error.config?.url || '';

    // Extract error message from response
    let message = 'An unexpected error occurred';
    if (typeof data === 'string') {
      message = data;
    } else if (data?.detail) {
      message = data.detail;
    } else if (data?.message) {
      message = data.message;
    } else if (data?.error) {
      message = data.error;
    }

    // Public endpoints that should NOT trigger session expiry logic
    const publicEndpoints = ['/auth/login', '/auth/signup', '/auth/forgot-password', '/auth/reset-password', '/settings', '/languages', '/health'];
    const isPublicEndpoint = publicEndpoints.some(endpoint => requestUrl.includes(endpoint));

    // Handle specific status codes
    if (status === 401) {
      // For public endpoints (like login), just pass through the error message
      if (isPublicEndpoint) {
        throw new ApiError(message, 401, 'AUTH_ERROR');
      }
      // For authenticated endpoints, clear token and redirect to login
      localStorage.removeItem('auth_token');
      window.location.href = '/login';
      throw new ApiError('Your session has expired. Please login again.', 401, 'UNAUTHORIZED');
    }

    if (status === 403) {
      throw new ApiError('You do not have permission to perform this action.', 403, 'FORBIDDEN');
    }

    if (status === 404) {
      throw new ApiError(message || 'Resource not found.', 404, 'NOT_FOUND');
    }

    if (status === 400) {
      throw new ApiError(message || 'Invalid request. Please check your input.', 400, 'BAD_REQUEST');
    }

    if (status === 422) {
      throw new ApiError(message || 'Validation error. Please check your input.', 422, 'VALIDATION_ERROR');
    }

    if (status >= 500) {
      throw new ApiError('Server error. Please try again later.', status, 'SERVER_ERROR');
    }

    // Generic error
    throw new ApiError(message, status);
  }
);

// Type definitions
export interface SignupData {
  email: string;
  password: string;
  name?: string;
}

export interface LoginData {
  email: string;
  password: string;
}

export interface OrderData {
  sourceLanguage: string;
  targetLanguage: string;
  serviceType: 'ai-only' | 'ai-human' | 'certified' | 'notarized';
  files: File[];
  options?: {
    humanReview?: boolean;
    certificate?: boolean;
    notarization?: boolean;
  };
}

// API methods
export const api = {
  // Settings
  getSettings: async () => {
    const response = await apiClient.get('/settings');
    return response.data;
  },

  // Auth
  login: async (data: LoginData) => {
    const response = await apiClient.post('/auth/login', data);
    return response.data;
  },

  signup: async (data: SignupData) => {
    const response = await apiClient.post('/auth/signup', data);
    return response.data;
  },

  logout: async () => {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('refresh_token');
  },

  refreshToken: async (refreshToken: string) => {
    const response = await apiClient.post('/auth/refresh', {}, {
      headers: {
        'Authorization': `Bearer ${refreshToken}`
      }
    });
    return response.data;
  },

  forgotPassword: async (email: string) => {
    const response = await apiClient.post('/auth/forgot-password', { email });
    return response.data;
  },

  resetPassword: async (token: string, new_password: string) => {
    const response = await apiClient.post('/auth/reset-password', {
      token,
      new_password
    });
    return response.data;
  },

  // File Upload
  uploadFile: async (file: File, onProgress?: (progress: number) => void) => {
    const formData = new FormData();
    formData.append('file', file);

    const response = await apiClient.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress && progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(progress);
        }
      },
    });
    return response.data;
  },

  // Orders
  createOrder: async (orderData: {
    documents: { filename: string; pages: number; type: string; document_id?: string }[];
    source_lang: string;
    target_lang: string;
    service_type: string;
    include_human_review?: boolean;
    include_certificate?: boolean;
    notarization_country?: string;
    express_service?: string;
  }) => {
    const response = await apiClient.post('/orders', orderData);
    return response.data;
  },

  getOrders: async () => {
    const response = await apiClient.get('/orders');
    return response.data;
  },

  getOrder: async (id: string) => {
    const response = await apiClient.get(`/orders/${id}`);
    return response.data;
  },

  updateOrderName: async (orderId: string, orderName: string) => {
    const response = await apiClient.patch(`/orders/${orderId}`, {
      order_name: orderName
    });
    return response.data;
  },

  getOrderDocuments: async (orderId: string) => {
    const response = await apiClient.get(`/orders/${orderId}/documents`);
    return response.data;
  },

  downloadDocument: async (documentId: string): Promise<Blob> => {
    const response = await apiClient.get(`/documents/${documentId}/download`, {
      responseType: 'blob',
    });
    return response.data;
  },

  viewDocument: async (documentId: string): Promise<string> => {
    const response = await apiClient.get(`/documents/${documentId}/view`, {
      responseType: 'text',
    });
    return response.data;
  },

  // Documents
  getDocument: async (id: string) => {
    const response = await apiClient.get(`/documents/${id}`);
    return response.data;
  },

  deleteDocument: async (id: string) => {
    const response = await apiClient.delete(`/documents/${id}`);
    return response.data;
  },

  // Document Output Generation
  generateDocumentOutput: async (documentId: string, options: {
    format: 'pdf' | 'docx' | 'bilingual_pdf' | 'bilingual_docx' | 'tmx' | 'csv' | 'tm_json';
    service_tier?: 'ai_text' | 'ai_ocr' | 'ai_human' | 'certified';
    include_watermark?: boolean;
    show_confidence?: boolean;
    bilingual_mode?: 'side_by_side' | 'interleaved' | 'two_column';
  }) => {
    const response = await apiClient.post(`/documents/${documentId}/generate`, options);
    return response.data;
  },

  downloadGeneratedOutput: async (documentId: string, format: string): Promise<Blob> => {
    const response = await apiClient.get(`/documents/${documentId}/download/${format}`, {
      responseType: 'blob',
    });
    return response.data;
  },

  getDocumentConfidence: async (documentId: string) => {
    const response = await apiClient.get(`/documents/${documentId}/confidence`);
    return response.data;
  },

  // Payments
  getPackages: async () => {
    const response = await apiClient.get('/payments/packages');
    return response.data;
  },

  createPayment: async (packageId: string, paymentMethod: string = 'PayNow') => {
    const response = await apiClient.post('/payments/create', {
      package_id: packageId,
      payment_method: paymentMethod
    });
    return response.data;
  },

  createCustomPayment: async (amount: number, paymentMethod: string = 'PayNow') => {
    const response = await apiClient.post('/payments/custom', {
      amount,
      payment_method: paymentMethod
    });
    return response.data;
  },

  verifyPayment: async (paymentId: string, transactionId: string, screenshotUrl?: string) => {
    const response = await apiClient.post('/payments/paynow/verify', {
      payment_id: paymentId,
      transaction_id: transactionId,
      screenshot_url: screenshotUrl
    });
    return response.data;
  },

  confirmPayment: async (paymentId: string, referenceNumber: string) => {
    const response = await apiClient.post('/payments/confirm', {
      payment_id: paymentId,
      reference_number: referenceNumber
    });
    return response.data;
  },

  // User
  getProfile: async () => {
    const response = await apiClient.get('/user/profile');
    return response.data;
  },

  getBalance: async () => {
    const response = await apiClient.get('/user/balance');
    return response.data;
  },

  updateProfile: async (data: any) => {
    const response = await apiClient.put('/user/profile', data);
    return response.data;
  },

  getTransactions: async (limit: number = 50) => {
    const response = await apiClient.get('/user/transactions', {
      params: { limit }
    });
    return response.data;
  },

  // Languages
  getLanguages: async () => {
    const response = await apiClient.get('/languages');
    return response.data;
  },

  // Pricing
  getPricingQuote: async (data: {
    documents: { filename: string; pages: number; type: string }[];
    source_lang: string;
    target_lang: string;
    include_human_review?: boolean;
    include_certificate?: boolean;
    notarization_country?: string;
    express_service?: string;
  }) => {
    const response = await apiClient.post('/pricing/quote', data);
    return response.data;
  },

  // Contact form
  submitContactForm: async (data: {
    name: string;
    email: string;
    subject: string;
    message: string;
  }) => {
    const response = await apiClient.post('/contact', data);
    return response.data;
  },

  // Health check
  getHealth: async () => {
    const response = await axios.get('https://translynx.ai/health');
    return response.data;
  },
};

export default api;
