import { Platform } from 'react-native';
import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AppConfig } from '@/config';

export const TOKEN_KEY = '@travelcam_token';

/**
 * Custom API Error class with HTTP status and network flags.
 */
export class ApiError extends Error {
  status?: number;
  isNotFound: boolean;
  isNetworkError: boolean;
  url?: string;

  constructor(message: string, status?: number, isNetworkError: boolean = false, url?: string) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
    this.isNotFound = status === 404;
    this.isNetworkError = isNetworkError;
    this.url = url;
  }
}

export const TARGET_DEV_IP = AppConfig.devIp;
export const TARGET_API_URL = AppConfig.apiBaseUrl;

/**
 * Cached active base URL once a candidate successfully connects with 200 OK.
 */
let cachedWorkingBaseUrl: string | null = null;

export function clearWorkingBaseUrlCache(): void {
  cachedWorkingBaseUrl = null;
}

/**
 * Sanitizes candidate URL: strips all whitespace, removes trailing slashes.
 */
function sanitizeUrl(raw: string): string {
  return raw.replace(/\s+/g, '').replace(/\/+$/, '');
}

/**
 * Extract the host development machine IP address from Expo bundler.
 */
function getExpoHostIp(): string | null {
  try {
    const hostUri =
      Constants.expoConfig?.hostUri ||
      (Constants as any).manifest2?.extra?.expoClient?.hostUri ||
      (Constants as any).manifest?.debuggerHost;

    if (hostUri && typeof hostUri === 'string') {
      const sanitized = hostUri.replace(/\s+/g, '');
      const ip = sanitized.split(':')[0];
      if (ip && ip !== 'localhost' && ip !== '127.0.0.1') {
        return ip;
      }
    }
  } catch (_) {
    // Ignore
  }
  return null;
}

/**
 * Retrieve API base URLs:
 * 1. Primary: .env declared value (EXPO_PUBLIC_API_URL via AppConfig.apiBaseUrl).
 * 2. Fallbacks: Expo bundler host IP, Android emulator, localhost.
 */
export function getCandidateBaseUrls(): string[] {
  if (cachedWorkingBaseUrl) {
    return [cachedWorkingBaseUrl];
  }

  const list: string[] = [];

  // 1. Primary source: AppConfig (driven by .env EXPO_PUBLIC_API_URL)
  const primaryUrl = sanitizeUrl(AppConfig.apiBaseUrl);
  if (primaryUrl && !list.includes(primaryUrl)) {
    list.push(primaryUrl);
  }

  // 2. Bundler host IP auto-detected from Expo connection
  const hostIp = getExpoHostIp();
  if (hostIp && !hostIp.startsWith('172.20.10.')) {
    const bundlerUrl = `http://${hostIp}:8000/api`;
    if (!list.includes(bundlerUrl)) {
      list.push(bundlerUrl);
    }
  }

  // 3. Platform emulators / localhost fallback
  if (Platform.OS === 'android') {
    const emuUrl = 'http://10.0.2.2:8000/api';
    if (!list.includes(emuUrl)) list.push(emuUrl);
  }

  const localUrl = 'http://127.0.0.1:8000/api';
  if (!list.includes(localUrl)) list.push(localUrl);

  return Array.from(new Set(list));
}

/**
 * Standard fetch with configurable timeout.
 */
async function fetchWithTimeout(url: string, options: RequestInit = {}, timeoutMs = 8000): Promise<Response> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const res = await fetch(url, {
      ...options,
      signal: controller.signal,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        ...(options.headers || {}),
      },
    });
    return res;
  } finally {
    clearTimeout(timer);
  }
}

/**
 * Send GET request to mobile API.
 * Iterates candidates until a working endpoint responds with 200 OK.
 */
export async function apiGet<T = any>(path: string): Promise<T> {
  const cleanPath = path.replace(/^\/+/, '');
  const candidates = getCandidateBaseUrls();
  let lastHttpError: ApiError | null = null;
  const networkErrors: string[] = [];
  const token = await apiClient.getToken().catch(() => null);
  const extraHeaders: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : {};

  for (let i = 0; i < candidates.length; i++) {
    const base = candidates[i];
    const baseUrl = sanitizeUrl(base);
    let pathForCandidate = cleanPath;
    if (baseUrl.endsWith('/api') && pathForCandidate.startsWith('api/')) {
      pathForCandidate = pathForCandidate.replace(/^api\//, '');
    }
    const url = `${baseUrl}/${pathForCandidate}`;
    const timeout = i === 0 ? 8000 : 2500;

    try {
      const response = await fetchWithTimeout(url, {
        method: 'GET',
        headers: extraHeaders,
      }, timeout);

      // Successful 2xx response: cache this working base URL and return data
      if (response.ok) {
        cachedWorkingBaseUrl = baseUrl;
        const json = await response.json();
        return json?.data !== undefined ? json.data : json;
      }

      // Non-2xx response (404, 500, etc.)
      let errorMessage = `HTTP Error ${response.status} (${response.statusText})`;
      try {
        const errJson = await response.json();
        if (errJson?.message) {
          errorMessage = errJson.message;
        }
      } catch (_) {}

      lastHttpError = new ApiError(errorMessage, response.status, false, url);
    } catch (err: any) {
      if (err instanceof ApiError) {
        lastHttpError = err;
      } else {
        networkErrors.push(`[${baseUrl}] ${err?.message || 'Connection failed'}`);
      }
    }
  }

  // If a candidate was reached but returned an HTTP error (e.g. 404, 500), throw that
  if (lastHttpError) {
    throw lastHttpError;
  }

  // All candidates failed to establish a network connection
  const primaryAttempt = candidates[0] || TARGET_API_URL;
  throw new ApiError(
    `Unable to connect to TravelCam server at ${primaryAttempt}. Please verify "php artisan serve --host=0.0.0.0 --port=8000" is running.`,
    0,
    true,
    primaryAttempt
  );
}

/**
 * Send GET request and return the full root JSON object (e.g. { status, layout, data }).
 */
export async function apiGetFull<T = any>(path: string): Promise<T> {
  const cleanPath = path.replace(/^\/+/, '');
  const candidates = getCandidateBaseUrls();
  let lastHttpError: ApiError | null = null;
  const networkErrors: string[] = [];
  const token = await apiClient.getToken().catch(() => null);
  const extraHeaders: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : {};

  for (let i = 0; i < candidates.length; i++) {
    const base = candidates[i];
    const baseUrl = sanitizeUrl(base);
    let pathForCandidate = cleanPath;
    if (baseUrl.endsWith('/api') && pathForCandidate.startsWith('api/')) {
      pathForCandidate = pathForCandidate.replace(/^api\//, '');
    }
    const url = `${baseUrl}/${pathForCandidate}`;
    const timeout = i === 0 ? 8000 : 2500;

    try {
      const response = await fetchWithTimeout(url, {
        method: 'GET',
        headers: extraHeaders,
      }, timeout);

      if (response.ok) {
        cachedWorkingBaseUrl = baseUrl;
        const json = await response.json();
        return json;
      }

      let errorMessage = `HTTP Error ${response.status} (${response.statusText})`;
      try {
        const errJson = await response.json();
        if (errJson?.message) {
          errorMessage = errJson.message;
        }
      } catch (_) {}

      lastHttpError = new ApiError(errorMessage, response.status, false, url);
    } catch (err: any) {
      if (err instanceof ApiError) {
        lastHttpError = err;
      } else {
        networkErrors.push(`[${baseUrl}] ${err?.message || 'Connection failed'}`);
      }
    }
  }

  if (lastHttpError) {
    throw lastHttpError;
  }

  const primaryAttempt = candidates[0] || TARGET_API_URL;
  throw new ApiError(
    `Unable to connect to TravelCam server at ${primaryAttempt}. Please verify "php artisan serve --host=0.0.0.0 --port=8000" is running.`,
    0,
    true,
    primaryAttempt
  );
}

/**
 * Send POST request to mobile API.
 */
export async function apiPost<T = any>(path: string, payload: any): Promise<T> {
  const cleanPath = path.replace(/^\/+/, '');
  const candidates = getCandidateBaseUrls();
  let lastHttpError: ApiError | null = null;
  const networkErrors: string[] = [];
  const token = await apiClient.getToken().catch(() => null);
  const extraHeaders: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : {};

  for (let i = 0; i < candidates.length; i++) {
    const base = candidates[i];
    const baseUrl = sanitizeUrl(base);
    let pathForCandidate = cleanPath;
    if (baseUrl.endsWith('/api') && pathForCandidate.startsWith('api/')) {
      pathForCandidate = pathForCandidate.replace(/^api\//, '');
    }
    const url = `${baseUrl}/${pathForCandidate}`;
    const timeout = i === 0 ? 8000 : 2500;

    try {
      const response = await fetchWithTimeout(url, {
        method: 'POST',
        headers: extraHeaders,
        body: JSON.stringify(payload),
      }, timeout);

      if (response.ok) {
        cachedWorkingBaseUrl = baseUrl;
        const json = await response.json();
        return json?.data !== undefined ? json.data : json;
      }

      let errorMessage = `HTTP Error ${response.status} (${response.statusText})`;
      try {
        const errJson = await response.json();
        if (errJson?.message) {
          errorMessage = errJson.message;
        }
      } catch (_) {}

      lastHttpError = new ApiError(errorMessage, response.status, false, url);
    } catch (err: any) {
      if (err instanceof ApiError) {
        lastHttpError = err;
      } else {
        networkErrors.push(`[${baseUrl}] ${err?.message || 'Connection failed'}`);
      }
    }
  }

  if (lastHttpError) {
    throw lastHttpError;
  }

  const primaryAttempt = candidates[0] || TARGET_API_URL;
  throw new ApiError(
    `Unable to connect to TravelCam server at ${primaryAttempt}. Please verify "php artisan serve --host=0.0.0.0 --port=8000" is running.`,
    0,
    true,
    primaryAttempt
  );
}

export interface ApiResponse<T = any> {
  status: number;
  data: T;
  ok: boolean;
}

/**
 * Universal mobile API Client with token handling and endpoint discovery.
 */
export const apiClient = {
  async getToken(): Promise<string | null> {
    try {
      return await AsyncStorage.getItem(TOKEN_KEY);
    } catch {
      return null;
    }
  },

  async setToken(token: string): Promise<void> {
    try {
      await AsyncStorage.setItem(TOKEN_KEY, token);
    } catch (e) {
      console.error('[apiClient] Failed to save token:', e);
    }
  },

  async clearToken(): Promise<void> {
    try {
      await AsyncStorage.removeItem(TOKEN_KEY);
    } catch (e) {
      console.error('[apiClient] Failed to clear token:', e);
    }
  },

  async request<T = any>(
    method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
    endpoint: string,
    body?: unknown
  ): Promise<ApiResponse<T>> {
    const cleanEndpoint = endpoint.trim().replace(/^\/+/, '');
    const token = await this.getToken();

    const headers: Record<string, string> = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    };

    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }

    const candidates = getCandidateBaseUrls();
    let lastResponse: Response | null = null;
    let lastData: any = null;

    for (let i = 0; i < candidates.length; i++) {
      const base = candidates[i];
      const baseUrl = sanitizeUrl(base);
      let pathForCandidate = cleanEndpoint;
      if (baseUrl.endsWith('/api') && pathForCandidate.startsWith('api/')) {
        pathForCandidate = pathForCandidate.replace(/^api\//, '');
      }
      const url = `${baseUrl}/${pathForCandidate}`;
      const timeout = i === 0 ? 8000 : 2500;

      try {
        const response = await fetchWithTimeout(url, {
          method,
          headers,
          body: body !== undefined ? JSON.stringify(body) : undefined,
        }, timeout);

        let data: any = {};
        try {
          data = await response.json();
        } catch (_) {
          data = {};
        }

        const normalizedData = {
          status: response.ok ? (data?.status || 'success') : (data?.status || 'error'),
          message:
            data?.message ||
            (response.ok ? 'Success' : `Request failed with status ${response.status}`),
          ...data,
        };

        if (response.ok) {
          cachedWorkingBaseUrl = baseUrl;
        }

        if (response.status !== 404 || candidates.length === 1) {
          if (response.status !== 404) {
            cachedWorkingBaseUrl = baseUrl;
          }
          return {
            status: response.status,
            data: normalizedData,
            ok: response.ok,
          };
        }

        lastResponse = response;
        lastData = normalizedData;
      } catch (err: any) {
        // Network timeout / connection error, try next candidate
      }
    }

    if (lastResponse) {
      return {
        status: lastResponse.status,
        data: lastData,
        ok: lastResponse.ok,
      };
    }

    return {
      status: 0,
      data: {
        status: 'error',
        message: 'Could not connect to server. Please check your network connection.',
      } as any,
      ok: false,
    };
  },

  get<T = any>(endpoint: string) {
    return this.request<T>('GET', endpoint);
  },

  post<T = any>(endpoint: string, payload?: unknown) {
    return this.request<T>('POST', endpoint, payload);
  },

  put<T = any>(endpoint: string, payload?: unknown) {
    return this.request<T>('PUT', endpoint, payload);
  },

  delete<T = any>(endpoint: string) {
    return this.request<T>('DELETE', endpoint);
  },
};

export default apiClient;

