package com.prank.happypranksounds.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.prank.happypranksounds.R;
import com.prank.happypranksounds.data.entity.HappyData;
import com.prank.happypranksounds.databinding.ActivitySoundBinding;
import com.prank.happypranksounds.topon.AdManager;
import com.prank.happypranksounds.topon.onActionListener;
import com.prank.happypranksounds.ui.viewmodel.HappyViewModel;

import java.io.IOException;
import java.util.Objects;

public class SoundActivity extends AppCompatActivity {
    private ActivitySoundBinding binding;
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;
    private int maxVolume, currentVolume;
    private boolean isPlaying = false;
    private boolean isLooping = false;
    private HappyData happyData;
    private HappyViewModel happyViewModel;

    private final BroadcastReceiver volumeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), "android.media.VOLUME_CHANGED_ACTION")) {
                int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                binding.seekBar.setProgress(currentVolume);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivitySoundBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();
    }

    private void initData() {
        happyData = (HappyData) getIntent().getSerializableExtra("audioData");
        if (happyData == null) {
            finish();
            return;
        }

        AdManager.loadAllAd();

        happyViewModel = new ViewModelProvider(this).get(HappyViewModel.class);

        IntentFilter filter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(volumeReceiver, filter);

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

    }

    private void initEvent() {
        binding.title.setText(happyData.getTitle());
        binding.back.setOnClickListener(v -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });
        });
        binding.favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateFavorite(happyData);
            }
        });
        binding.loop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLooping = !isLooping;
                binding.loop.setImageResource(isLooping ? R.drawable.loop : R.drawable.un_loop);
                if (mediaPlayer != null) {
                    mediaPlayer.setLooping(isLooping);
                }
            }
        });
        binding.play.setOnClickListener(v -> playAudio());
        binding.seekBar.setMax(maxVolume);
        binding.seekBar.setProgress(currentVolume);
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        loadImage();
        loadIsFavorite(happyData);
    }

    private void playAudio() {
        String audioUrl = happyData.getMp3Url();

        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

            try {
                if (audioUrl.startsWith("content://")) {
                    Uri audioUri = Uri.parse(audioUrl);
                    mediaPlayer.setDataSource(this, audioUri);
                } else {
                    mediaPlayer.setDataSource(audioUrl);
                }

                mediaPlayer.prepareAsync();

                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                        binding.play.setImageResource(R.drawable.pause);
                        isPlaying = true;
                        mediaPlayer.setLooping(isLooping);
                    }
                });

                mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        Toast.makeText(SoundActivity.this, "Error playing audio", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });

                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (!isLooping) {
                            binding.play.setImageResource(R.drawable.play);
                            isPlaying = false;
                        }
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(SoundActivity.this, "Error setting data source", Toast.LENGTH_SHORT).show();
            }
        } else {
            if (isPlaying) {
                mediaPlayer.pause();
                binding.play.setImageResource(R.drawable.play);
            } else {
                mediaPlayer.start();
                binding.play.setImageResource(R.drawable.pause);
            }
            isPlaying = !isPlaying;
        }
    }

    private void loadIsFavorite(HappyData happyData) {
        boolean isFavorite = happyData.isFavorite();
        updateFavoriteIcon(isFavorite);
    }

    private void loadImage() {
        Glide.with(this)
                .load(happyData.getPreUrl())
                .placeholder(R.mipmap.placeholder)
                .error(R.mipmap.placeholder)
                .transform(new RoundedCorners(16))
                .into(binding.image);
    }

    private void updateFavorite(HappyData happyData) {
        boolean isFavorite = happyViewModel.toggleFavorite(happyData);
        updateFavoriteIcon(isFavorite);
    }

    private void updateFavoriteIcon(boolean isFavorite) {
        binding.favorite.setImageResource(isFavorite ? R.drawable.favorite : R.drawable.un_favorite);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(volumeReceiver);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        binding = null;
    }
}