package com.example.bem;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.VibrationEffect;
import android.os.Vibrator;

import androidx.core.app.NotificationCompat;

public class AlarmSoundService extends Service {
    
    private static final String CHANNEL_ID = "alarm_sound_channel";
    private static final int NOTIFICATION_ID = 2001;
    private MediaPlayer mediaPlayer;
    private Vibrator vibrator;
    
    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && "STOP_ALARM".equals(intent.getAction())) {
            stopSelf();
            return START_NOT_STICKY;
        }
        
        String title = intent.getStringExtra("alarm_title");
        String ringtoneUriString = intent.getStringExtra("ringtone_uri");
        
        startForeground(NOTIFICATION_ID, createNotification(title));
        
        playAlarmSound(ringtoneUriString);
        vibratePhone();
        
        new android.os.Handler().postDelayed(this::stopSelf, 60000);
        
        return START_NOT_STICKY;
    }
    
    private void playAlarmSound(String ringtoneUriString) {
        try {
            Uri soundUri;
            if (ringtoneUriString != null && !ringtoneUriString.isEmpty()) {
                soundUri = Uri.parse(ringtoneUriString);
            } else {
                soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                if (soundUri == null) {
                    soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            }
            
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(this, soundUri);
            
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            mediaPlayer.setAudioAttributes(audioAttributes);
            
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (audioManager != null) {
                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
                audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0);
            }
            
            mediaPlayer.setLooping(true);
            mediaPlayer.setVolume(1.0f, 1.0f);
            
            mediaPlayer.setOnPreparedListener(mp -> {
                mp.start();
            });
            
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                mp.reset();
                return true;
            });
            
            mediaPlayer.prepareAsync();
            
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Uri defaultUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                if (defaultUri != null && mediaPlayer != null) {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(this, defaultUri);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    private void vibratePhone() {
        vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null && vibrator.hasVibrator()) {
            long[] pattern = {
                0,      // Início
                400,    // Vibra 400ms
                1200,   // Pausa 1.2s
                400,    // Vibra 400ms
                3000    // Pausa 3s antes de repetir
            };
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createWaveform(pattern, 0));
            } else {
                vibrator.vibrate(pattern, 0);
            }
        }
    }
    
    private Notification createNotification(String title) {
        Intent stopIntent = new Intent(this, AlarmSoundService.class);
        stopIntent.setAction("STOP_ALARM");
        PendingIntent stopPendingIntent = PendingIntent.getService(
                this, 
                0, 
                stopIntent, 
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        
        Intent openIntent = new Intent(this, MainActivity.class);
        openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent openPendingIntent = PendingIntent.getActivity(
                this, 
                0, 
                openIntent, 
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
                .setContentTitle("⏰ " + (title != null ? title : "Alarme de Medicamento"))
                .setContentText("Hora de tomar o medicamento! Toque para abrir.")
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_ALARM)
                .setOngoing(true)
                .setAutoCancel(false)
                .setContentIntent(openPendingIntent)
                .addAction(android.R.drawable.ic_media_pause, "Parar", stopPendingIntent)
                .build();
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Serviço de Alarme",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("Toca o alarme de medicação");
            channel.setSound(null, null);
            
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
        
        if (vibrator != null) {
            vibrator.cancel();
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

