package com.offline.music.player.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.DrawableCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.offline.music.player.R;
import com.offline.music.player.databinding.ActivityAplayBinding;
import com.offline.music.player.javabean.A_data.AudioItem;
import com.offline.music.player.max.MaxManager;
import com.offline.music.player.max.onAdAfterAction;
import com.offline.music.player.service.MusicPlayerForegroundService;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class A_PlayActivity extends BaseActivity<ActivityAplayBinding> {

    private MusicPlayerForegroundService musicService; // 音乐播放服务
    private boolean isBound = false; // 服务绑定状态
    private boolean isBackground; // 背景状态
    private Handler progressHandler; // 用于更新进度的Handler
    private List<TextView> textViews = new ArrayList<>(); // 存储变换颜色的文字
    private boolean isTimerOff = false; // 标志位

    // 服务连接对象
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicPlayerForegroundService.MusicBinder) service).getService();
            isBound = true;

            // 设置观察者
            musicService.getIsPlaying().observe(A_PlayActivity.this, this::updatePlayButton);

            musicService.getFileName().observe(A_PlayActivity.this, vb.songTitle::setText);

            // 更新进度条和时间
            updateSeekBarAndTime(); // 添加这一行以确保服务连接时更新UI

            musicService.startUpdatingProgress(); // 启动进度更新
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false; // 服务断开时更新状态
        }

        // 更新播放按钮状态
        private void updatePlayButton(Boolean isPlaying) {
            if (isPlaying != null) {
                vb.playButton.setBackgroundResource(isPlaying ? R.drawable.pause_green : R.drawable.play_green);
                if (isPlaying) {
                    musicService.resumeTimer();
                } else {
                    musicService.pauseTimer();
                }
            }
        }
    };

    @Override
    protected ActivityAplayBinding getViewBinding() {
        return ActivityAplayBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onCreateInit() {
        MaxManager.onLoadAd();
        textViews.add(vb.songTitle);
        textViews.add(vb.artistAlbumText);
        textViews.add(vb.current);
        textViews.add(vb.time);
        textViews.add(vb.nowPlayingText);

        loadBackgroundPreference(); // 加载之前保存的背景状态

        updateSeekBarAndTime();
        if (musicService != null) {
            musicService.startUpdatingProgress();
        }

        // 从Intent获取音频项
        AudioItem audioItem = (AudioItem) getIntent().getSerializableExtra("Path");
        if (audioItem == null) {
            finish(); // 若未获取到音频路径则结束Activity
            return;
        }

        Glide.with(this)
                .load("file:///android_asset/" + audioItem.getImage())
                .placeholder(R.mipmap.playing_background) // 默认图片
                .into(vb.recordImage); // 加载专辑图片

        Glide.with(this)
                .asBitmap()
                .load("file:///android_asset/" + audioItem.getImage())
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        // 对图片进行高斯模糊处理
                        Bitmap blurredBitmap = blurBitmap(A_PlayActivity.this, resource, 5);

                        // 将模糊后的图片作为背景设置到 vb.topContainer
                        Drawable blurredDrawable = new BitmapDrawable(getResources(), blurredBitmap);
                        vb.topContainer.setBackground(blurredDrawable);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // 可选：处理图片加载被清除的情况
                    }
                });


        startMusicService(audioItem); // 启动音乐服务
        setupPlayButtonClickListener(); // 设置播放按钮的点击事件

    }


    public Bitmap blurBitmap(Context context, Bitmap originalBitmap, int iterations) {
        // 创建 RenderScript 对象
        RenderScript renderScript = RenderScript.create(context);

        // 创建 Allocation 对象
        Allocation input = Allocation.createFromBitmap(renderScript, originalBitmap);
        Allocation output = Allocation.createTyped(renderScript, input.getType());

        // 创建模糊脚本对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));

        // 设置模糊半径
        blurScript.setRadius(25);  // 设置最大模糊半径

        // 执行多次模糊操作
        for (int i = 0; i < iterations; i++) {
            blurScript.setInput(input);
            blurScript.forEach(output);
            // 将结果复制到输入 Allocation
            input.copyFrom(output);
        }

        // 将模糊后的结果写入到 Bitmap 中
        output.copyTo(originalBitmap);

        renderScript.destroy();  // 释放 RenderScript 对象

        return originalBitmap;
    }


    @Override
    protected void onInitClick() {
        vb.songSeekbar.setOnSeekBarChangeListener(new SeekBarListener()); // 设置进度条监听
        vb.repeatButton.setOnClickListener(v -> {
            MaxManager.startShowMaxAd(A_PlayActivity.this, new onAdAfterAction() {
                @Override
                public void onAction() {
                    showTimerDialog();
                }
            });
        }); // 设置定时器按钮的点击事件
        vb.prevButton.setOnClickListener(v -> toggleBackground()); // 设置切换背景按钮的点击事件
    }

    // 启动音乐服务并绑定
    private void startMusicService(AudioItem audioItem) {
        Intent serviceIntent = new Intent(this, MusicPlayerForegroundService.class);
        serviceIntent.putExtra("Path", audioItem);
        Log.d("A_PlayActivity", "Path: " + audioItem);
        startService(serviceIntent); // 启动服务
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); // 绑定服务
    }

    // 设置播放按钮的点击事件
    private void setupPlayButtonClickListener() {
        vb.playButton.setOnClickListener(v -> {
          MaxManager.startShowMaxAd(A_PlayActivity.this, new onAdAfterAction() {
              @Override
              public void onAction() {
                  if (isBound && musicService != null) {
                      // 根据播放状态切换播放/暂停
                      if (Boolean.TRUE.equals(musicService.getIsPlaying().getValue())) {
                          musicService.pauseAudio();
                      } else {
                          musicService.resumeAudio();
                      }
                  }
                  if (musicService != null) {
                      musicService.startUpdatingProgress();
                  }
              }
          });
        });

        vb.backButton.setOnClickListener(v -> MaxManager.startShowMaxAd(this, new onAdAfterAction() {
            @Override
            public void onAction() {
                finish();
            }
        })); // 返回按钮点击事件
    }


    // 更新进度条和时间显示
    private void updateSeekBarAndTime() {
        if (isBound && musicService != null) {
            // 观察当前播放进度
            musicService.getCurrentPositionLiveData().observe(this, position -> {
                if (musicService.getDurationLiveData().getValue() != null) {
                    int duration = musicService.getDurationLiveData().getValue();
                    if (duration > 0) {
                        vb.songSeekbar.setProgress((int) ((position / (float) duration) * 100));
                        vb.current.setText(formatTime(position));
                    }
                }
            });

            // 观察音频总时长
            musicService.getDurationLiveData().observe(this, duration -> {
                vb.time.setText(formatTime(duration));
            });
        }
    }

    // 切换背景
    private void toggleBackground() {
        isBackground = !isBackground; // 切换背景状态

        // 根据背景状态设置背景和控件的样式
        if (isBackground) {
            setDarkTheme();  // 暗色主题
        } else {
            setLightTheme(); // 亮色主题
        }

        saveBackgroundPreference(); // 保存当前背景状态
    }

    private void setDarkTheme() {
        vb.topContainer.setBackgroundResource(R.mipmap.blur);
        vb.bottomContainer.setBackgroundResource(R.color.black);
//        vb.recordImage.setBackgroundResource(R.mipmap.playing_background);
        setTextColor(Color.WHITE);
        vb.prevButton.setImageResource(R.drawable.sleep);
        vb.repeatButton.setImageResource(R.drawable.timing);
        updateSeekBarColor(Color.WHITE, Color.parseColor("#4DFFFFFF"));
    }

    private void setLightTheme() {
        vb.topContainer.setBackgroundColor(Color.WHITE);
        vb.bottomContainer.setBackgroundColor(Color.WHITE);
        vb.backButton.setImageResource(R.drawable.arrow_left_black);
//        vb.recordImage.setBackgroundResource(R.mipmap.playing_background_light);
        setTextColor(Color.BLACK);
        vb.prevButton.setImageResource(R.drawable.light);
        vb.repeatButton.setImageResource(R.drawable.timing_drak);
        updateSeekBarColor(Color.parseColor("#2680F988"), Color.parseColor("#2680F988"));
    }

    private void updateSeekBarColor(int thumbColor, int progressColor) {
        Drawable thumbDrawable = vb.songSeekbar.getThumb();
        if (thumbDrawable != null) {
            DrawableCompat.setTint(thumbDrawable, thumbColor);
            vb.songSeekbar.setThumb(thumbDrawable);
        }

        Drawable progressDrawable = vb.songSeekbar.getProgressDrawable();
        if (progressDrawable != null) {
            DrawableCompat.setTint(progressDrawable, progressColor);
            vb.songSeekbar.setProgressDrawable(progressDrawable);
        }
    }


    // 保存背景状态到SharedPreferences
    private void saveBackgroundPreference() {
        SharedPreferences sharedPreferences = getSharedPreferences("AppPreferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isBackground", isBackground);
        editor.apply();
    }

    // 从SharedPreferences加载背景状态
    private void loadBackgroundPreference() {
        SharedPreferences sharedPreferences = getSharedPreferences("AppPreferences", MODE_PRIVATE);
        isBackground = sharedPreferences.getBoolean("isBackground", true); // 默认值为 true

        // 根据保存的状态设置背景
        vb.rootLayout.setBackgroundResource(isBackground ? R.color.dark_music : R.color.white);
        vb.backButton.setImageResource(isBackground ? R.drawable.arrow_left : R.drawable.arrow_left_black);
        vb.prevButton.setImageResource(isBackground ? R.drawable.sleep : R.drawable.light);
        vb.repeatButton.setImageResource(isBackground ? R.drawable.timing : R.drawable.timing_drak);
        setTextColor(isBackground ? Color.WHITE : Color.BLACK);
    }

    // 设置文字颜色
    private void setTextColor(int color) {
        for (TextView textView : textViews) {
            textView.setTextColor(color);
        }
    }

    // 显示定时器对话框
    private void showTimerDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.timing_dialog, null);
        bottomSheetDialog.setContentView(dialogView);

        RadioGroup timerOptions = dialogView.findViewById(R.id.timerOptions);
        TextView time = dialogView.findViewById(R.id.timerLabel);

        // 读取上次选中的 radioButton ID
        SharedPreferences sharedPreferences = getSharedPreferences("TimerPreferences", MODE_PRIVATE);
        int selectedId = sharedPreferences.getInt("selectedTimerOption", R.id.radioOff); // 默认选项为 radioOff
        timerOptions.check(selectedId); // 设置默认选中的 RadioButton

        timerOptions.setOnCheckedChangeListener((group, checkedId) -> {
            int duration = 0; // 用于保存定时时长

            if (checkedId == R.id.radioOff) {
                musicService.stopTimer();
                time.setText("Timing off");
                isTimerOff = true; // 设置标志位为 true
//                Toast.makeText(getApplicationContext(), "定时关闭已取消", Toast.LENGTH_SHORT).show();
            } else if (checkedId == R.id.radio10) {
                duration = 10 * 60 * 1000; // 10分钟
                isTimerOff = false;
            } else if (checkedId == R.id.radio20) {
                duration = 20 * 60 * 1000; // 20分钟
                isTimerOff = false;
            } else if (checkedId == R.id.radio30) {
                duration = 30 * 60 * 1000; // 30分钟
                isTimerOff = false;
            } else if (checkedId == R.id.radio60) {
                duration = 60 * 60 * 1000; // 60分钟
                isTimerOff = false;
            } else if (checkedId == R.id.radio90) {
                duration = 90 * 60 * 1000; // 90分钟
                isTimerOff = false;
            }
            if (duration > 0) {
//                Toast.makeText(getApplicationContext(), "定时设置为 " + (duration / 60000) + " 分钟", Toast.LENGTH_SHORT).show();
                musicService.startTimer(duration);
            }

            // 保存选中的 radioButton ID 到 SharedPreferences
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("selectedTimerOption", checkedId);
            editor.apply();
        });

        // 观察remainingTimeLiveData，实时更新UI
        musicService.getRemainingTimeLiveData().observe(A_PlayActivity.this, remainingTime -> {
            if (!isTimerOff) {
                time.setText("Count down " + formatTime(remainingTime));
            }
        });

        bottomSheetDialog.show(); // 显示 BottomSheetDialog
    }

    // 进度条的监听器
    private class SeekBarListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser && musicService != null && isBound) {
                int duration = musicService.getDuration();
                if (duration > 0) {
                    int newPosition = (int) ((progress / 100.0) * duration);
                    musicService.seekTo(newPosition); // 设置音频进度
                }
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // 用户开始拖动进度条时触发
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            musicService.startUpdatingProgress();
            ; // 拖动结束后重新启动进度更新
        }

    }

    // 格式化时间显示
    private String formatTime(int milliseconds) {
        int minutes = (milliseconds / 1000) / 60;
        int seconds = (milliseconds / 1000) % 60;
        return String.format(Locale.getDefault(), "%d:%02d", minutes, seconds);
    }

    @Override
    public boolean isFullScreen() {
        return true; // 设置为全屏
    }

    @Override
    public boolean statusBarLight() {
        return false; // 设置状态栏为非亮色
    }

    @Override
    public boolean showPanel() {
        return false;
    }

    @Override
    public void onClick(View v) {
        // 处理其他点击事件
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(serviceConnection); // 解绑服务
            isBound = false;
        }
        if (progressHandler != null) {
            progressHandler.removeCallbacksAndMessages(null); // 移除所有更新任务
            progressHandler = null; // 释放引用
        }
    }
}
