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.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.offline.music.player.R;
import com.offline.music.player.adapter.A_HomeViewPagerAdapter;
import com.offline.music.player.databinding.ActivityAhomeBinding;
import com.offline.music.player.databinding.HomeTabCustomBinding;
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.Locale;

public class A_HomeActivity extends BaseActivity<ActivityAhomeBinding> {

    private MusicPlayerForegroundService musicService; // 音乐播放服务
    private boolean isBound = false; // 服务是否绑定

    private final int[] defaultIcons = {R.drawable.home_unselect, R.drawable.import_unselect}; // 默认图标
    private final int[] selectedIcons = {R.drawable.home_select, R.drawable.import_select}; // 选中图标

    @Override
    protected ActivityAhomeBinding getViewBinding() {
        return ActivityAhomeBinding.inflate(getLayoutInflater()); // 获取视图绑定
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicPlayerForegroundService.MusicBinder) service).getService(); // 获取服务实例
            isBound = true; // 服务已绑定
            updatePlayButtonState(); // 更新播放按钮状态
            updateProgress(); // 启动进度更新
            observeIsPlaying(); // 观察播放状态变化

            musicService.getFileName().observe(A_HomeActivity.this, vb.topText::setText); // 设置标题
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false; // 服务已断开
        }
    };

    @Override
    protected void onCreateInit() {

        MaxManager.onLoadAd();
        Intent serviceIntent = new Intent(this, MusicPlayerForegroundService.class);
        startService(serviceIntent); // 启动音乐播放服务
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); // 绑定服务

        // 初始化界面
        vb.homeContainer.setVisibility(View.GONE);
        vb.pause.setOnClickListener(v -> togglePlayPause()); // 设置暂停/播放按钮点击事件
        vb.homeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              MaxManager.startShowMaxAd(A_HomeActivity.this, new onAdAfterAction() {
                  @Override
                  public void onAction() {
                      AudioItem audioItem = musicService.getAudioItem();
                      Intent intent = new Intent(A_HomeActivity.this, A_PlayActivity.class);
                      intent.putExtra("Path", audioItem);
                      startActivity(intent);
                  }
              });
            }
        });
        setupProgressBar(); // 设置进度条
        setupViewPager(); // 设置ViewPager
        setupTabLayout(); // 设置TabLayout
    }

    @Override
    protected void onInitClick() {
        // 处理其他点击事件
    }

    @Override
    public boolean isFullScreen() {
        return true;
    }

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

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

    // 设置进度条
    private void setupProgressBar() {
        vb.circularProgressBar.setMaxProgress(100); // 设置进度条最大值
    }

    // 切换播放/暂停
    private void togglePlayPause() {
        if (isBound && musicService != null) {
            // 判断当前播放状态并切换
            if (musicService.getIsPlaying().getValue() != null && musicService.getIsPlaying().getValue()) {
                musicService.pauseAudio(); // 暂停播放
            } else {
                musicService.resumeAudio(); // 恢复播放
            }
            updatePlayButtonState(); // 更新播放按钮图标
            updateProgress();
        }
    }

    // 更新播放按钮的状态
    private void updatePlayButtonState() {
        if (isBound && musicService != null && musicService.getIsPlaying().getValue() != null) {
            boolean isPlaying = musicService.getIsPlaying().getValue(); // 获取播放状态
            vb.pause.setImageResource(isPlaying ? R.drawable.pause : R.drawable.play); // 更新图标
        }
    }

    // 更新进度
    private void updateProgress() {
        if (isBound && musicService != null) {
            // 开始更新播放进度
            musicService.startUpdatingProgress();

            // 观察当前播放位置
            musicService.getCurrentPositionLiveData().observe(this, position -> {
                if (musicService.getDurationLiveData().getValue() != null) {
                    int duration = musicService.getDurationLiveData().getValue();
                    vb.bottomText1.setText(formatTime(position)); // 更新当前时间文本

                    if (duration > 0) {
                        int progress = (int) ((position / (float) duration) * 100); // 计算进度
                        vb.circularProgressBar.setProgress(progress); // 更新进度条
                    }
                }
            });

            // 观察音频总时长
            musicService.getDurationLiveData().observe(this, duration -> {
                vb.bottomText2.setText(formatTime(duration)); // 更新总时间文本
            });
        }
    }

    // 观察播放状态变化
    private void observeIsPlaying() {
        if (isBound && musicService != null) {
            musicService.getIsPlaying().observe(this, isPlaying -> {
                if (isPlaying != null) {
                    vb.pause.setImageResource(isPlaying ? R.drawable.pause : R.drawable.play); // 更新播放按钮图标
                    if (isPlaying) {
                        vb.homeContainer.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
    }

    // 设置ViewPager
    private void setupViewPager() {
        A_HomeViewPagerAdapter adapter = new A_HomeViewPagerAdapter(this); // 创建适配器
        vb.homeViewpager.setAdapter(adapter); // 设置适配器
        vb.homeViewpager.setUserInputEnabled(false); // 禁用用户输入
    }

    // 设置TabLayout
    private void setupTabLayout() {
        new TabLayoutMediator(vb.homeTabLayout, vb.homeViewpager, (tab, position) -> {
            HomeTabCustomBinding tabBinding = HomeTabCustomBinding.inflate(LayoutInflater.from(this)); // 自定义Tab布局
            tab.setCustomView(tabBinding.getRoot()); // 设置自定义视图
            tabBinding.homeIcon.setImageResource(defaultIcons[position]); // 设置默认图标
        }).attach(); // 附加TabLayout和ViewPager

        vb.homeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateTabIcon(tab, true); // 更新选中图标
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabIcon(tab, false); // 更新未选中图标
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });

        // 默认选择第一个标签
        TabLayout.Tab firstTab = vb.homeTabLayout.getTabAt(0);
        if (firstTab != null) {
            firstTab.select(); // 选择第一个标签
            updateTabIcon(firstTab, true); // 更新选中图标
        }
    }

    // 更新Tab图标
    private void updateTabIcon(TabLayout.Tab tab, boolean isSelected) {
        View customView = tab.getCustomView();
        if (customView != null) {
            HomeTabCustomBinding tabBinding = HomeTabCustomBinding.bind(customView);
            tabBinding.homeIcon.setImageResource(isSelected ? selectedIcons[tab.getPosition()] : defaultIcons[tab.getPosition()]); // 更新图标
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection); // 解绑服务
    }

    // 格式化时间
    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 void onClick(View v) {
        // 处理其他点击事件
    }
}
