package com.miraclegarden.smsmessage.network;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.miraclegarden.smsmessage.model.ApiError;
import com.miraclegarden.smsmessage.model.AppNotificationSettings;
import com.miraclegarden.smsmessage.model.BankInfo;
import com.miraclegarden.smsmessage.model.BankListResponse;
import com.miraclegarden.smsmessage.model.LoginResponse;
import com.miraclegarden.smsmessage.model.UploadNotificationResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * API服务类 - 封装所有网络请求
 */
public class ApiService {
    private static final String TAG = "ApiService";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String BASE_URL = "https://www.judy88.xin";

    private final OkHttpClient httpClient;
    private final Gson gson;
    private final TokenManager tokenManager;

    public ApiService(Context context) {
        this.tokenManager = TokenManager.getInstance(context);
        this.gson = new Gson();
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 登录接口
     */
    public void login(String username, String password, ApiCallback<LoginResponse> callback) {
        try {
            JSONObject json = new JSONObject();
            json.put("username", username);
            json.put("password", password);
            json.put("clientType", "app");

            Request request = new Request.Builder()
                    .url(BASE_URL + "/api/auth/login")
                    .header("Content-Type", "application/json")
                    .post(RequestBody.create(json.toString(), JSON))
                    .build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    handleResponse(response, LoginResponse.class, callback);
                }
            });
        } catch (JSONException e) {
            callback.onError(new ApiError(0, "JSON_ERROR", e.getMessage()));
        }
    }

    /**
     * 修改密码
     */
    public void changePassword(String oldPassword, String newPassword, ApiCallback<Void> callback) {
        try {
            JSONObject json = new JSONObject();
            json.put("oldPassword", oldPassword);
            json.put("newPassword", newPassword);

            Request request = buildAuthRequest("/api/auth/change-password")
                    .post(RequestBody.create(json.toString(), JSON))
                    .build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    if (response.isSuccessful()) {
                        callback.onSuccess(null);
                    } else {
                        callback.onError(parseError(response));
                    }
                }
            });
        } catch (JSONException e) {
            callback.onError(new ApiError(0, "JSON_ERROR", e.getMessage()));
        }
    }

    /**
     * 获取银行账户列表
     */
    public void getBankList(ApiCallback<List<BankInfo>> callback) {
        Request request = buildAuthRequest("/api/bank-email-parser/banks")
                .get()
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                handleResponse(response, BankListResponse.class, new ApiCallback<BankListResponse>() {
                    @Override
                    public void onSuccess(BankListResponse result) {
                        callback.onSuccess(result.getBanks());
                    }

                    @Override
                    public void onError(ApiError error) {
                        callback.onError(error);
                    }
                });
            }
        });
    }

    /**
     * 创建银行账户
     */
    public void createBank(BankInfo bankInfo, ApiCallback<BankInfo> callback) {
        try {
            JSONObject json = new JSONObject();
            json.put("bankName", bankInfo.getBankName());
            json.put("account", bankInfo.getAccount());
            if (bankInfo.getRemark() != null) {
                json.put("remark", bankInfo.getRemark());
            }

            Request request = buildAuthRequest("/api/bank-email-parser/banks")
                    .post(RequestBody.create(json.toString(), JSON))
                    .build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    handleResponse(response, BankInfo.class, callback);
                }
            });
        } catch (JSONException e) {
            callback.onError(new ApiError(0, "JSON_ERROR", e.getMessage()));
        }
    }

    /**
     * 更新银行账户
     */
    public void updateBank(String bankId, BankInfo bankInfo, ApiCallback<BankInfo> callback) {
        try {
            JSONObject json = new JSONObject();
            json.put("bankName", bankInfo.getBankName());
            json.put("account", bankInfo.getAccount());
            if (bankInfo.getRemark() != null) {
                json.put("remark", bankInfo.getRemark());
            }

            Request request = buildAuthRequest("/api/bank-email-parser/banks/" + bankId)
                    .patch(RequestBody.create(json.toString(), JSON))
                    .build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    handleResponse(response, BankInfo.class, callback);
                }
            });
        } catch (JSONException e) {
            callback.onError(new ApiError(0, "JSON_ERROR", e.getMessage()));
        }
    }

    /**
     * 删除银行账户
     */
    public void deleteBank(String bankId, ApiCallback<Void> callback) {
        Request request = buildAuthRequest("/api/bank-email-parser/banks/" + bankId)
                .delete()
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                if (response.isSuccessful()) {
                    callback.onSuccess(null);
                } else {
                    callback.onError(parseError(response));
                }
            }
        });
    }

    /**
     * 获取App通知设置
     */
    public void getAppNotificationSettings(ApiCallback<AppNotificationSettings> callback) {
        Request request = buildAuthRequest("/api/settings/app-notification")
                .get()
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                handleResponse(response, AppNotificationSettings.class, callback);
            }
        });
    }

    /**
     * 更新App通知设置
     */
    public void updateAppNotificationSettings(boolean enabled, ApiCallback<Void> callback) {
        try {
            JSONObject json = new JSONObject();
            json.put("appNotificationAutoProcessEnabled", enabled);

            Request request = buildAuthRequest("/api/settings/app-notification")
                    .patch(RequestBody.create(json.toString(), JSON))
                    .build();

            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    if (response.isSuccessful()) {
                        callback.onSuccess(null);
                    } else {
                        callback.onError(parseError(response));
                    }
                }
            });
        } catch (JSONException e) {
            callback.onError(new ApiError(0, "JSON_ERROR", e.getMessage()));
        }
    }

    /**
     * 上传App通知
     */
    public void uploadNotification(String jsonPayload, ApiCallback<UploadNotificationResponse> callback) {
        Request request = buildAuthRequest("/api/bills/app-upload")
                .post(RequestBody.create(jsonPayload, JSON))
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onError(new ApiError(0, "NETWORK_ERROR", e.getMessage()));
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                handleResponse(response, UploadNotificationResponse.class, callback);
            }
        });
    }

    /**
     * 构建带认证的请求
     */
    private Request.Builder buildAuthRequest(String path) {
        Request.Builder builder = new Request.Builder()
                .url(BASE_URL + path)
                .header("Content-Type", "application/json");

        String authHeader = tokenManager.getAuthHeader();
        if (authHeader != null) {
            builder.header("Authorization", authHeader);
        }

        return builder;
    }

    /**
     * 处理响应
     */
    private <T> void handleResponse(Response response, Class<T> clazz, ApiCallback<T> callback) {
        try {
            if (response.isSuccessful()) {
                String body = response.body() != null ? response.body().string() : "";
                T result = gson.fromJson(body, clazz);
                callback.onSuccess(result);
            } else {
                callback.onError(parseError(response));
            }
        } catch (Exception e) {
            Log.e(TAG, "Response handling error", e);
            callback.onError(new ApiError(0, "PARSE_ERROR", e.getMessage()));
        } finally {
            response.close();
        }
    }

    /**
     * 解析错误响应
     */
    private ApiError parseError(Response response) {
        try {
            int code = response.code();
            String body = response.body() != null ? response.body().string() : "";

            try {
                JSONObject json = new JSONObject(body);
                String error = json.optString("error", "UNKNOWN_ERROR");
                String message = json.optString("message", body);
                return new ApiError(code, error, message);
            } catch (JSONException e) {
                return new ApiError(code, "HTTP_ERROR", body.isEmpty() ? "HTTP " + code : body);
            }
        } catch (IOException e) {
            return new ApiError(response.code(), "READ_ERROR", e.getMessage());
        }
    }

    /**
     * API回调接口
     */
    public interface ApiCallback<T> {
        void onSuccess(T result);
        void onError(ApiError error);
    }
}
