import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../constants/api_endpoints.dart';
import '../storage/local_storage.dart';
import 'api_exception.dart';
import 'api_response.dart';

/// 网络配置常量
class NetworkConfig {
  static const String baseUrl = ApiEndpoints.baseUrl;
  static const Duration connectTimeout = Duration(seconds: 15);
  static const Duration receiveTimeout = Duration(seconds: 15);
  static const Duration sendTimeout = Duration(seconds: 15);
}

/// Dio 网络客户端
class DioClient {
  late final Dio _dio;

  DioClient() {
    _dio = _createDio();
    _setupInterceptors();
    debugPrint('DioClient initialized with baseUrl: ${NetworkConfig.baseUrl}');
  }

  Dio _createDio() {
    return Dio(BaseOptions(
      baseUrl: NetworkConfig.baseUrl,
      connectTimeout: NetworkConfig.connectTimeout,
      receiveTimeout: NetworkConfig.receiveTimeout,
      sendTimeout: NetworkConfig.sendTimeout,
      headers: {'Content-Type': 'application/json'},
    ));
  }

  void _setupInterceptors() {
    _dio.interceptors.addAll([
      _AuthInterceptor(),
      _LoggingInterceptor(),
    ]);
  }

  /// GET 请求
  Future<ApiResponse<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.get(path, queryParameters: queryParameters);
      return _handleResponse<T>(response, fromJson);
    } on DioException catch (e) {
      return _handleError<T>(e);
    }
  }

  /// POST 请求
  Future<ApiResponse<T>> post<T>(
    String path, {
    dynamic data,
    T Function(dynamic)? fromJson,
  }) async {
    try {
      final response = await _dio.post(path, data: data);
      return _handleResponse<T>(response, fromJson);
    } on DioException catch (e) {
      return _handleError<T>(e);
    }
  }

  ApiResponse<T> _handleResponse<T>(
    Response response,
    T Function(dynamic)? fromJson,
  ) {
    final data = response.data;
    if (data is Map<String, dynamic>) {
      return ApiResponse.fromJson(data, fromJson);
    }
    return ApiResponse.fail('响应数据格式错误');
  }

  ApiResponse<T> _handleError<T>(DioException e) {
    // 详细错误日志
    debugPrint('=== Network Error ===');
    debugPrint('Type: ${e.type}');
    debugPrint('Message: ${e.message}');
    debugPrint('URL: ${e.requestOptions.uri}');
    debugPrint('StatusCode: ${e.response?.statusCode}');
    debugPrint('ResponseData: ${e.response?.data}');
    debugPrint('====================');

    if (_isUnauthorized(e)) {
      _clearUserData();
      return ApiResponse.unauthorized('登录已过期，请重新登录');
    }

    final message = _getErrorMessage(e);
    return ApiResponse.fail(message);
  }

  bool _isUnauthorized(DioException e) {
    return e.response?.statusCode == 401;
  }

  void _clearUserData() {
    LocalStorage.clearUserData();
  }

  String _getErrorMessage(DioException e) {
    switch (e.type) {
      case DioExceptionType.connectionTimeout:
        return '连接超时，请检查网络';
      case DioExceptionType.sendTimeout:
        return '发送超时，请重试';
      case DioExceptionType.receiveTimeout:
        return '响应超时，请重试';
      case DioExceptionType.connectionError:
        return '网络连接失败，请检查网络设置';
      case DioExceptionType.badResponse:
        final statusCode = e.response?.statusCode;
        if (statusCode == 500) {
          return '服务器内部错误';
        } else if (statusCode == 502 || statusCode == 503) {
          return '服务暂时不可用';
        }
        return '服务器错误 ($statusCode)';
      default:
        return e.message ?? '网络请求失败';
    }
  }
}

/// 日志拦截器
class _LoggingInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    debugPrint('┌──────────────────────────────────────────────────────────');
    debugPrint('│ REQUEST: ${options.method} ${options.uri}');
    debugPrint('│ Headers: ${options.headers}');
    if (options.data != null) {
      debugPrint('│ Data: ${options.data}');
    }
    debugPrint('└──────────────────────────────────────────────────────────');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    debugPrint('┌──────────────────────────────────────────────────────────');
    debugPrint('│ RESPONSE: ${response.statusCode} ${response.requestOptions.uri}');
    debugPrint('│ Data: ${response.data}');
    debugPrint('└──────────────────────────────────────────────────────────');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    debugPrint('┌──────────────────────────────────────────────────────────');
    debugPrint('│ ERROR: ${err.type} ${err.requestOptions.uri}');
    debugPrint('│ Message: ${err.message}');
    debugPrint('│ StatusCode: ${err.response?.statusCode}');
    debugPrint('└──────────────────────────────────────────────────────────');
    super.onError(err, handler);
  }
}

/// 认证拦截器
class _AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final token = LocalStorage.getToken();
    if (token?.isNotEmpty == true) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response?.statusCode == 401) {
      LocalStorage.clearUserData();
    }
    super.onError(err, handler);
  }
}
