package br.com.trimsy.notify;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;

import org.json.JSONArray;
import org.json.JSONObject;

public final class NotifyHub {
    public static final String CHANNEL_ID = "trimsy_alerts";
    public static final String ACTION_SHOW = "br.com.trimsy.notify.SHOW";
    public static final String PREFS = "trimsy_notify";
    public static final String KEY_PENDING = "pending";
    public static final String EXTRA_ID = "id";
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_BODY = "body";
    public static final String EXTRA_PAYLOAD = "payload";
    public static final String EXTRA_AT = "at";
    public static final String LAUNCH_PAYLOAD = "trimsy_payload";

    private NotifyHub() {}

    public static void ensureChannel(Context ctx) {
        if (Build.VERSION.SDK_INT < 26) return;
        NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm == null) return;
        NotificationChannel channel = nm.getNotificationChannel(CHANNEL_ID);
        if (channel != null) return;
        channel = new NotificationChannel(CHANNEL_ID, "Trimsy One", NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Avisos da agenda e reservas");
        channel.enableVibration(true);
        channel.setLightColor(Color.parseColor("#6426E8"));
        nm.createNotificationChannel(channel);
    }

    public static boolean notificationsAllowed(Context ctx) {
        if (Build.VERSION.SDK_INT < 33) return true;
        return ctx.checkSelfPermission("android.permission.POST_NOTIFICATIONS")
            == android.content.pm.PackageManager.PERMISSION_GRANTED;
    }

    public static int icon(Context ctx) {
        int id = ctx.getResources().getIdentifier("ic_trimsy_notify", "drawable", ctx.getPackageName());
        return id != 0 ? id : android.R.drawable.ic_popup_reminder;
    }

    public static PendingIntent launchIntent(Context ctx, String payload) {
        Intent launch = ctx.getPackageManager().getLaunchIntentForPackage(ctx.getPackageName());
        if (launch == null) {
            launch = new Intent();
            launch.setClassName(ctx, "br.com.barbergenerator.MainActivity");
        }
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (payload != null && payload.length() > 0) {
            launch.putExtra(LAUNCH_PAYLOAD, payload);
        }
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE;
        return PendingIntent.getActivity(ctx, 71001, launch, flags);
    }

    public static void show(Context ctx, int id, String title, String body, String payload) {
        if (id == 0) id = 1;
        ensureChannel(ctx);
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= 26) {
            builder = new Notification.Builder(ctx, CHANNEL_ID);
        } else {
            builder = new Notification.Builder(ctx);
        }
        builder.setSmallIcon(icon(ctx))
            .setContentTitle(title != null ? title : "Trimsy One")
            .setContentText(body != null ? body : "")
            .setStyle(new Notification.BigTextStyle().bigText(body != null ? body : ""))
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(launchIntent(ctx, payload));
        if (Build.VERSION.SDK_INT >= 21) {
            builder.setColor(Color.parseColor("#6426E8"));
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        }
        if (Build.VERSION.SDK_INT < 26) {
            builder.setPriority(Notification.PRIORITY_HIGH);
        }
        NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm != null) nm.notify(id, builder.build());
    }

    public static PendingIntent alarmIntent(Context ctx, JSONObject item) {
        int id = item.optInt(EXTRA_ID, 1);
        Intent intent = new Intent(ctx, NotifyReceiver.class);
        intent.setAction(ACTION_SHOW);
        intent.putExtra(EXTRA_ID, id);
        intent.putExtra(EXTRA_TITLE, item.optString(EXTRA_TITLE));
        intent.putExtra(EXTRA_BODY, item.optString(EXTRA_BODY));
        intent.putExtra(EXTRA_PAYLOAD, item.optString(EXTRA_PAYLOAD));
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE;
        return PendingIntent.getBroadcast(ctx, id, intent, flags);
    }

    public static void schedule(Context ctx, JSONObject item) {
        if (item == null) return;
        int id = item.optInt(EXTRA_ID, 1);
        long at = item.optLong(EXTRA_AT, 0);
        if (at <= System.currentTimeMillis() + 2000) {
            show(ctx, id, item.optString(EXTRA_TITLE), item.optString(EXTRA_BODY), item.optString(EXTRA_PAYLOAD));
            removePending(ctx, id);
            return;
        }
        savePending(ctx, item);
        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
        if (am == null) return;
        PendingIntent pi = alarmIntent(ctx, item);
        try {
            if (Build.VERSION.SDK_INT >= 31 && !am.canScheduleExactAlarms()) {
                am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
            } else if (Build.VERSION.SDK_INT >= 23) {
                am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
            } else {
                am.set(AlarmManager.RTC_WAKEUP, at, pi);
            }
        } catch (Exception e) {
            try {
                am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
            } catch (Exception ignored) {}
        }
    }

    public static void cancel(Context ctx, int id) {
        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
        JSONObject stub = new JSONObject();
        try {
            stub.put(EXTRA_ID, id);
        } catch (Exception ignored) {}
        if (am != null) {
            try { am.cancel(alarmIntent(ctx, stub)); } catch (Exception ignored) {}
        }
        NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm != null) nm.cancel(id);
        removePending(ctx, id);
    }

    public static void cancelAll(Context ctx) {
        JSONArray pending = loadPending(ctx);
        for (int i = 0; i < pending.length(); i++) {
            JSONObject item = pending.optJSONObject(i);
            if (item == null) continue;
            cancel(ctx, item.optInt(EXTRA_ID, 0));
        }
        ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY_PENDING, "[]").apply();
        NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        if (nm != null) nm.cancelAll();
    }

    public static void restore(Context ctx) {
        JSONArray pending = loadPending(ctx);
        long now = System.currentTimeMillis();
        for (int i = 0; i < pending.length(); i++) {
            JSONObject item = pending.optJSONObject(i);
            if (item == null) continue;
            long at = item.optLong(EXTRA_AT, 0);
            if (at > 0 && at <= now + 2000) {
                show(ctx, item.optInt(EXTRA_ID, 1), item.optString(EXTRA_TITLE), item.optString(EXTRA_BODY), item.optString(EXTRA_PAYLOAD));
                removePending(ctx, item.optInt(EXTRA_ID, 0));
            } else {
                schedule(ctx, item);
            }
        }
    }

    private static JSONArray loadPending(Context ctx) {
        try {
            return new JSONArray(ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY_PENDING, "[]"));
        } catch (Exception e) {
            return new JSONArray();
        }
    }

    private static void savePending(Context ctx, JSONObject item) {
        int id = item.optInt(EXTRA_ID, 0);
        JSONArray next = new JSONArray();
        JSONArray prev = loadPending(ctx);
        for (int i = 0; i < prev.length(); i++) {
            JSONObject row = prev.optJSONObject(i);
            if (row == null || row.optInt(EXTRA_ID, 0) == id) continue;
            next.put(row);
        }
        next.put(item);
        ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY_PENDING, next.toString()).apply();
    }

    public static void removePending(Context ctx, int id) {
        JSONArray next = new JSONArray();
        JSONArray prev = loadPending(ctx);
        for (int i = 0; i < prev.length(); i++) {
            JSONObject row = prev.optJSONObject(i);
            if (row == null || row.optInt(EXTRA_ID, 0) == id) continue;
            next.put(row);
        }
        ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY_PENDING, next.toString()).apply();
    }
}
