import { useCallback } from 'react';
import { Alert } from 'react-native';
import ky, { HTTPError, type Options as KyOptions } from 'ky';
import { storage } from '@/App';

// Token存储键
const TOKEN_KEY = 'auth_token';

// 错误码映射
const ERROR_CODE_MAP: Record<string, string> = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误,请反馈给管理员',
};

// Token相关工具函数
export const getToken = (): string | undefined => {
  return storage.getString(TOKEN_KEY);
};

export const setToken = (token: string): void => {
  storage.set(TOKEN_KEY, token);
};

export const removeToken = (): void => {
  storage.delete(TOKEN_KEY);
};

// Token失败处理（跳转登录）
const tokenFailureHandler = () => {
  removeToken();
  // TODO: 导航到登录页面
  // 可以通过全局事件或导航ref来实现
  Alert.alert('提示', '登录已过期，请重新登录');
};

// 显示错误提示
const showErrorToast = (message: string) => {
  Alert.alert('错误', message);
};

// 请求响应数据结构
interface ApiResponse<T = any> {
  code: number;
  msg?: string;
  data?: T;
}

// 创建基础ky实例
const baseUrl = 'https://recipe-muse.com:8443';

const createKyInstance = () => {
  return ky.create({
    prefixUrl: baseUrl,
    timeout: 3 * 60 * 1000, // 3分钟超时
    headers: {
      'Content-Type': 'application/json',
    },
    hooks: {
      // 请求前钩子 - 添加token
      beforeRequest: [
        (request) => {
          const token = getToken();
          if (token) {
            request.headers.set('Authorization', `Bearer ${token}`);
          }
        },
      ],
      // 响应后钩子 - 处理业务错误码
      afterResponse: [
        async (request, options, response) => {
          // 如果HTTP状态码正常，检查业务状态码
          if (response.ok) {
            const data = (await response.json()) as ApiResponse;
            const code = data.code ?? 200;
            const msg = ERROR_CODE_MAP[String(code)] ?? data.msg ?? ERROR_CODE_MAP['default'];

            // 处理业务错误码
            if (code === 401) {
              tokenFailureHandler();
              throw new Error(msg);
            } else if (code === 500) {
              showErrorToast(msg);
              throw new Error(msg);
            } else if (code !== 200) {
              showErrorToast(msg);
              throw new Error(msg);
            }

            // 返回修改后的响应（只返回data部分）
            return new Response(JSON.stringify(data.data), {
              status: response.status,
              statusText: response.statusText,
              headers: response.headers,
            });
          }
          return response;
        },
      ],
    },
  });
};

// 全局ky实例
const kyInstance = createKyInstance();

// 错误处理函数
const handleRequestError = (error: unknown): never => {
  let message = '网络请求失败';

  if (error instanceof HTTPError) {
    const statusCode = error.response.status;
    
    // 处理HTTP错误
    if (statusCode === 401) {
      tokenFailureHandler();
      message = '认证失败，请重新登录';
    } else if (statusCode >= 500) {
      message = '服务器错误，请稍后重试';
    } else if (statusCode >= 400) {
      message = '请求参数错误';
    }

    // 尝试获取错误响应体
    error.response.json().then((data: any) => {
      const codeStart = String(data.code).substring(0, 2);
      
      // Token认证错误
      if (codeStart === '10') {
        tokenFailureHandler();
      }
      
      if (data.message) {
        message = data.message;
      }
    }).catch(() => {
      // JSON解析失败，使用默认错误消息
    });
  } else if (error instanceof Error) {
    // 网络错误
    if (error.message.includes('Network Error') || error.message.includes('network')) {
      message = '网络连接异常';
    } else if (error.message.includes('timeout')) {
      message = '请求超时，请重试';
    } else {
      message = error.message;
    }
  }

  setTimeout(() => {
    Alert.alert('错误', message);
  }, 0);

  throw error;
};

// 自定义请求配置接口
interface RequestConfig extends KyOptions {
  skipErrorHandler?: boolean; // 跳过全局错误处理
  skipAuth?: boolean; // 跳过认证token
}

/**
 * useRequest Hook
 * 提供统一的API请求功能
 */
export const useRequest = () => {
  // GET请求
  const get = useCallback(async <T = any>(
    url: string,
    options?: RequestConfig
  ): Promise<T> => {
    try {
      const { skipErrorHandler, skipAuth, ...kyOptions } = options ?? {};
      
      const requestOptions: KyOptions = {
        ...kyOptions,
        method: 'get',
      };

      // 如果跳过认证，移除Authorization头
      if (skipAuth) {
        requestOptions.hooks = {
          beforeRequest: [
            (request) => {
              request.headers.delete('Authorization');
            },
          ],
        };
      }

      const response = await kyInstance(url, requestOptions).json<T>();
      return response;
    } catch (error) {
      if (!options?.skipErrorHandler) {
        handleRequestError(error);
      }
      throw error;
    }
  }, []);

  // POST请求
  const post = useCallback(async <T = any>(
    url: string,
    data?: any,
    options?: RequestConfig
  ): Promise<T> => {
    try {
      const { skipErrorHandler, skipAuth, ...kyOptions } = options ?? {};
      
      const requestOptions: KyOptions = {
        ...kyOptions,
        method: 'post',
        json: data,
      };

      if (skipAuth) {
        requestOptions.hooks = {
          beforeRequest: [
            (request) => {
              request.headers.delete('Authorization');
            },
          ],
        };
      }

      const response = await kyInstance(url, requestOptions).json<T>();
      return response;
    } catch (error) {
      if (!options?.skipErrorHandler) {
        handleRequestError(error);
      }
      throw error;
    }
  }, []);

  // PUT请求
  const put = useCallback(async <T = any>(
    url: string,
    data?: any,
    options?: RequestConfig
  ): Promise<T> => {
    try {
      const { skipErrorHandler, skipAuth, ...kyOptions } = options ?? {};
      
      const requestOptions: KyOptions = {
        ...kyOptions,
        method: 'put',
        json: data,
      };

      if (skipAuth) {
        requestOptions.hooks = {
          beforeRequest: [
            (request) => {
              request.headers.delete('Authorization');
            },
          ],
        };
      }

      const response = await kyInstance(url, requestOptions).json<T>();
      return response;
    } catch (error) {
      if (!options?.skipErrorHandler) {
        handleRequestError(error);
      }
      throw error;
    }
  }, []);

  // DELETE请求
  const del = useCallback(async <T = any>(
    url: string,
    options?: RequestConfig
  ): Promise<T> => {
    try {
      const { skipErrorHandler, skipAuth, ...kyOptions } = options ?? {};
      
      const requestOptions: KyOptions = {
        ...kyOptions,
        method: 'delete',
      };

      if (skipAuth) {
        requestOptions.hooks = {
          beforeRequest: [
            (request) => {
              request.headers.delete('Authorization');
            },
          ],
        };
      }

      const response = await kyInstance(url, requestOptions).json<T>();
      return response;
    } catch (error) {
      if (!options?.skipErrorHandler) {
        handleRequestError(error);
      }
      throw error;
    }
  }, []);

  // 通用请求方法
  const request = useCallback(async <T = any>(
    url: string,
    options?: RequestConfig
  ): Promise<T> => {
    try {
      const { skipErrorHandler, skipAuth, ...kyOptions } = options ?? {};
      
      const requestOptions: KyOptions = kyOptions;

      if (skipAuth) {
        requestOptions.hooks = {
          beforeRequest: [
            (request) => {
              request.headers.delete('Authorization');
            },
          ],
        };
      }

      const response = await kyInstance(url, requestOptions).json<T>();
      return response;
    } catch (error) {
      if (!options?.skipErrorHandler) {
        handleRequestError(error);
      }
      throw error;
    }
  }, []);

  return {
    get,
    post,
    put,
    delete: del,
    request,
  };
};

// 导出ky实例供直接使用
export const http = kyInstance;

// 默认导出
export default useRequest;
