import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import useAuthStore from '../../store/useAuthStore';

const rawBase = import.meta.env.VITE_API_URL || 'http://localhost:8000';
const normalized = String(rawBase).replace(/\/$/, '');
const API_BASE_URL = /\/api(\/?$)/i.test(normalized)
  ? normalized
  : normalized + '/api';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; 
const RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504];

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

const retryRequest = async (
  error: AxiosError,
  retryCount: number = 0
): Promise<any> => {
  const config = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
  
  
  if (
    config._retry ||
    retryCount >= MAX_RETRIES ||
    !error.config ||
    !error.response ||
    !RETRYABLE_STATUS_CODES.includes(error.response.status)
  ) {
    return Promise.reject(error);
  }

  config._retry = true;
  
  
  const delay = RETRY_DELAY * Math.pow(2, retryCount);
  await new Promise(resolve => setTimeout(resolve, delay));

  console.log(`Retrying request (${retryCount + 1}/${MAX_RETRIES}): ${config.url}`);
  
  return apiClient.request(config);
};

apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    
    if (config.url && typeof config.url === 'string') {
      if (config.url.startsWith('/api/')) {
        config.url = config.url.replace(/^\/api/, '');
      }
      config.url = config.url.replace(/\/\/+/, '/');
    }

    
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type'];
    }

    
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    
    const requestId = crypto.randomUUID ? crypto.randomUUID() : 
      `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    config.headers['X-Request-ID'] = requestId;

    
    (config as any).metadata = { startTime: new Date() };

    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

apiClient.interceptors.response.use(
  (response) => {
    
    const config = response.config as InternalAxiosRequestConfig & { metadata?: any };
    if (config.metadata?.startTime) {
      const duration = new Date().getTime() - config.metadata.startTime.getTime();
      if (duration > 1000) { 
        console.warn(`Slow request detected: ${config.url} took ${duration}ms`);
      }
    }

    
    const requestId = response.headers['x-request-id'];
    if (requestId && import.meta.env.DEV) {
      console.debug(`Request completed: ${config.url} [${requestId}]`);
    }

    return response;
  },
  async (error: AxiosError) => {
    const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };

    
    if (!error.response) {
      if (error.code === 'ECONNABORTED') {
        return Promise.reject({
          ...error,
          message: 'Request timeout. Please check your connection and try again.',
        });
      }
      
      
      if (originalRequest && !originalRequest._retry) {
        return retryRequest(error);
      }

      console.error('Network error:', error);
      return Promise.reject({
        ...error,
        message: 'Network error. Please check your internet connection.',
      });
    }

    const status = error.response.status;
    const requestId = error.response.headers['x-request-id'];

    
    if (status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      
      // Update auth store state
      useAuthStore.getState().logout().catch(() => {
        // Ignore logout errors, just clear the state
        useAuthStore.setState({
          token: null,
          userInfo: null,
          isAuthenticated: false,
          isLoading: false,
        });
      });
      
      // Dispatch custom event to trigger login modal
      window.dispatchEvent(new CustomEvent('auth:logout', { 
        detail: { message: 'Session expired. Please login again.' } 
      }));
      
      const errorMessage = (error.response?.data as any)?.message || 'Session expired. Please login again.';
      return Promise.reject({
        ...error,
        message: errorMessage,
      });
    }

    
    if (status === 403) {
      const errorMessage = (error.response?.data as any)?.message || 'You do not have permission to access this resource.';
      return Promise.reject({
        ...error,
        message: errorMessage,
      });
    }

    
    if (status === 404) {
      const errorMessage = (error.response?.data as any)?.message || 'Resource not found.';
      return Promise.reject({
        ...error,
        message: errorMessage,
      });
    }

    
    if (status === 429) {
      const retryAfter = error.response.headers['retry-after'];
      return Promise.reject({
        ...error,
        message: `Too many requests. ${retryAfter ? `Please try again after ${retryAfter} seconds.` : 'Please try again later.'}`,
        retryAfter: retryAfter ? parseInt(retryAfter) : undefined,
      });
    }

    
    if (status >= 500 && status < 600) {
      if (originalRequest && !originalRequest._retry) {
        return retryRequest(error);
      }
      
      console.error(`Server error [${requestId || 'unknown'}]:`, error);
      const errorMessage = (error.response?.data as any)?.message || 'Server error. Please try again later.';
      return Promise.reject({
        ...error,
        message: errorMessage,
        requestId,
      });
    }

    
    if (status === 400) {
      const errorData = error.response.data as any;
      return Promise.reject({
        ...error,
        message: errorData?.message || errorData?.errors?.[0]?.message || 'Invalid request. Please check your input.',
        errors: errorData?.errors || [],
      });
    }

    
    const errorMessage = (error.response.data as any)?.message || error.message || 'An error occurred';
    return Promise.reject({
      ...error,
      message: errorMessage,
      requestId,
    });
  }
);

export default apiClient;
