package com.yourorg.discordclone;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;

import androidx.core.app.NotificationCompat;

public class VoiceConnectionService extends Service {

    public static final String ACTION_START = "com.yourorg.discordclone.VOICE_START";
    public static final String ACTION_STOP = "com.yourorg.discordclone.VOICE_STOP";
    public static final String ACTION_UPDATE = "com.yourorg.discordclone.VOICE_UPDATE";

    public static final String EXTRA_CHANNEL_NAME = "channelName";
    public static final String EXTRA_IS_MUTED = "isMuted";
    public static final String EXTRA_IS_DEAFENED = "isDeafened";

    private static final String CHANNEL_ID = "voice_call";
    private static final int NOTIFICATION_ID = 1001;

    private PowerManager.WakeLock wakeLock;
    private String channelName = "Voice";
    private boolean isMuted = false;
    private boolean isDeafened = false;

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) return START_STICKY;

        String action = intent.getAction();
        if (action == null) return START_STICKY;

        switch (action) {
            case ACTION_START:
                channelName = intent.getStringExtra(EXTRA_CHANNEL_NAME);
                if (channelName == null) channelName = "Voice";
                isMuted = intent.getBooleanExtra(EXTRA_IS_MUTED, false);
                isDeafened = intent.getBooleanExtra(EXTRA_IS_DEAFENED, false);
                acquireWakeLock();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    startForeground(NOTIFICATION_ID, buildNotification(),
                            android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE);
                } else {
                    startForeground(NOTIFICATION_ID, buildNotification());
                }
                break;

            case ACTION_UPDATE:
                if (intent.hasExtra(EXTRA_CHANNEL_NAME)) {
                    channelName = intent.getStringExtra(EXTRA_CHANNEL_NAME);
                }
                if (intent.hasExtra(EXTRA_IS_MUTED)) {
                    isMuted = intent.getBooleanExtra(EXTRA_IS_MUTED, false);
                }
                if (intent.hasExtra(EXTRA_IS_DEAFENED)) {
                    isDeafened = intent.getBooleanExtra(EXTRA_IS_DEAFENED, false);
                }
                NotificationManager nm = getSystemService(NotificationManager.class);
                if (nm != null) {
                    nm.notify(NOTIFICATION_ID, buildNotification());
                }
                break;

            case ACTION_STOP:
                releaseWakeLock();
                stopForeground(true);
                stopSelf();
                break;
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        releaseWakeLock();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Voice Call",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Ongoing voice call notification");
            channel.setShowBadge(false);
            NotificationManager nm = getSystemService(NotificationManager.class);
            if (nm != null) {
                nm.createNotificationChannel(channel);
            }
        }
    }

    private Notification buildNotification() {
        // Tap intent — bring app to foreground
        Intent tapIntent = new Intent(this, MainActivity.class);
        tapIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent tapPending = PendingIntent.getActivity(
                this, 0, tapIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        // Disconnect action
        PendingIntent disconnectPending = makeBroadcastPending(
                VoiceNotificationReceiver.ACTION_DISCONNECT, 1);

        // Mute action
        PendingIntent mutePending = makeBroadcastPending(
                VoiceNotificationReceiver.ACTION_TOGGLE_MUTE, 2);

        // Deafen action
        PendingIntent deafenPending = makeBroadcastPending(
                VoiceNotificationReceiver.ACTION_TOGGLE_DEAFEN, 3);

        String muteLabel = isMuted ? "Unmute" : "Mute";
        String deafenLabel = isDeafened ? "Undeafen" : "Deafen";

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_voice_notification)
                .setContentTitle("Voice Connected")
                .setContentText(channelName)
                .setOngoing(true)
                .setSilent(true)
                .setContentIntent(tapPending)
                .addAction(0, "Disconnect", disconnectPending)
                .addAction(0, muteLabel, mutePending)
                .addAction(0, deafenLabel, deafenPending)
                .setCategory(NotificationCompat.CATEGORY_CALL)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
    }

    private PendingIntent makeBroadcastPending(String action, int requestCode) {
        Intent intent = new Intent(this, VoiceNotificationReceiver.class);
        intent.setAction(action);
        return PendingIntent.getBroadcast(
                this, requestCode, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
    }

    private void acquireWakeLock() {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            if (pm != null) {
                wakeLock = pm.newWakeLock(
                        PowerManager.PARTIAL_WAKE_LOCK,
                        "discordclone:voicecall"
                );
                wakeLock.acquire();
            }
        }
    }

    private void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
        }
    }
}
