package com.atmob.voiceai.module.voiceai;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.atmob.app.lib.base.BaseFragment;
import com.atmob.common.logging.AtmobLog;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.bean.TypeListBean;
import com.atmob.voiceai.data.api.bean.VoiceListBean;
import com.atmob.voiceai.databinding.FragmentVoiceAiBinding;
import com.atmob.voiceai.databinding.ItemVoiceAiTabBinding;
import com.atmob.voiceai.module.clonevoice.CloneVoiceFragment;
import com.atmob.voiceai.module.main.MainActivity;
import com.atmob.voiceai.utils.BoxingUtil;
import com.atmob.voiceai.utils.GridLayoutItemDecoration;
import com.atmob.voiceai.utils.SmoothScrollGridLayoutManager;
import com.atmob.voiceai.utils.ToastUtil;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class VoiceAIFragment extends BaseFragment<FragmentVoiceAiBinding> {


    private VoiceAIViewModel voiceViewModel;
    private VoiceAIListAdapter voiceAIListAdapter;

    private ExoPlayer player;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initObserver();
    }

    private void initObserver() {
        voiceViewModel.getScrollToBean().observe(getViewLifecycleOwner(), bean -> {
            if (bean != null) {
                int beanPosition = voiceAIListAdapter.getBeanPosition(bean);
                if (beanPosition != -1) {
                    binding.ryVoiceView.smoothScrollToPosition(beanPosition);
                }
            }
        });
        voiceViewModel.getNotifyBean().observe(getViewLifecycleOwner(), bean -> {
            if (bean == null) {
                return;
            }
            voiceAIListAdapter.notify(bean);
        });
        voiceViewModel.getScrollToTabPosition().observe(getViewLifecycleOwner(), index -> binding.voiceTab.selectTab(binding.voiceTab.getTabAt(BoxingUtil.boxing(index))));
        voiceViewModel.getPlayExampleVoice().observe(getViewLifecycleOwner(), this::playExampleVoice);
        voiceViewModel.getShowGenerateAd().observe(getViewLifecycleOwner(), o -> {
            //TODO 显示广告
            voiceViewModel.seeAdGenerate();
        });
        voiceViewModel.getVoiceDetailList().observe(getViewLifecycleOwner(), list -> voiceAIListAdapter.submit(list.first, () -> {
                    if (list.second != null) {
                        voiceViewModel.scrollToListPosition(list.second.getId());
                    } else {
                        binding.ryVoiceView.scrollToPosition(0);
                    }
                })
        );
        voiceViewModel.getVoiceTypeList().observe(getViewLifecycleOwner(), list -> {
            if (list == null || list.isEmpty()) {
                return;
            }
            binding.voiceTab.removeAllTabs();
            for (int i = 0; i < list.size(); i++) {
                TypeListBean typeListBean = list.get(i);
                TabLayout.Tab tab = binding.voiceTab.newTab();
                ItemVoiceAiTabBinding itemBinding = ItemVoiceAiTabBinding.inflate(getLayoutInflater());
                itemBinding.tabTitle.setText(typeListBean.getName());
                tab.setCustomView(itemBinding.getRoot());
                tab.setTag(itemBinding);
                binding.voiceTab.addTab(tab);
                itemBinding.getRoot().setOnClickListener(v -> {
                    tab.select();
                    voiceViewModel.refreshVoiceList(String.valueOf(typeListBean.getId()));
                });
                if (i == 0) {
                    itemBinding.getRoot().performClick();
                }
            }
        });
    }

    private void initView() {
        initExoPlayer();
        initTabLayout();
        initVoiceList();
    }


    private void initExoPlayer() {
        player = new ExoPlayer.Builder(requireContext()).build();
    }

    private void initVoiceList() {
        voiceAIListAdapter = new VoiceAIListAdapter(getViewLifecycleOwner());
        voiceAIListAdapter.setActionHandler(new VoiceAIListAdapter.ActionHandler() {
            @Override
            public void addClick() {
                MainActivity.start(requireActivity(), CloneVoiceFragment.class);
            }

            @Override
            public void voiceItemClick(@NonNull VoiceListBean voiceListBean) {
                voiceViewModel.voiceItemClick(voiceListBean);
            }
        });
        binding.ryVoiceView.setAdapter(voiceAIListAdapter);
        SmoothScrollGridLayoutManager gridLayoutManager = new SmoothScrollGridLayoutManager(getContext(), 4);
        binding.ryVoiceView.setLayoutManager(gridLayoutManager);
        GridLayoutItemDecoration gridLayoutItemDecoration = new GridLayoutItemDecoration(4, 0.0222222222222222f, 0.0222222222222222f, false);
        binding.ryVoiceView.addItemDecoration(gridLayoutItemDecoration);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (voiceAIListAdapter.getItemViewType(position) == VoiceAIListAdapter.TYPE_FOOT) {
                    return 4;
                }
                return 1;
            }
        });
    }

    private void playExampleVoice(VoiceListBean voiceListBean) {
        if (player.isPlaying() || player.isLoading()) {
            player.stop();
        }
        if (voiceListBean == null) {
            return;
        }
        Uri videoUri = Uri.parse(voiceListBean.getVoiceUrl());
        MediaItem mediaItem = MediaItem.fromUri(videoUri);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.setPlayWhenReady(true);
        voiceListBean.setVoicePlayState(VoiceListBean.VoicePlayState.LOADING);
        player.addListener(new Player.Listener() {

            @Override
            public void onPlayerError(PlaybackException error) {
                AtmobLog.d("zk", "onPlayerError: " + error.getMessage());
                voiceListBean.setVoicePlayState(VoiceListBean.VoicePlayState.INITIAL);
                ToastUtil.show(R.string.voice_play_error, ToastUtil.LENGTH_SHORT);
            }

            @Override
            public void onPlaybackStateChanged(int state) {
                AtmobLog.d("zk", "onPlaybackStateChanged: " + state + "  " + voiceListBean.getName() + "  " + voiceListBean.getVoiceUrl());
                if (Player.STATE_ENDED == state) {
                    voiceViewModel.setVoicePlayEnd();
                }
            }
        });
    }

    private void initTabLayout() {
        binding.voiceTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Object tag = tab.getTag();
                ItemVoiceAiTabBinding itemBinding = tag instanceof ItemVoiceAiTabBinding ? ((ItemVoiceAiTabBinding) tag) : null;
                if (itemBinding == null) {
                    return;
                }
                itemBinding.tabTitle.setTextColor(getResources().getColor(R.color.colorPrimary));
                itemBinding.tabTitle.setBackground(getResources().getDrawable(R.drawable.bg_voice_ai_tab_selected));
            }

            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Object tag = tab.getTag();
                ItemVoiceAiTabBinding itemBinding = tag instanceof ItemVoiceAiTabBinding ? ((ItemVoiceAiTabBinding) tag) : null;
                if (itemBinding == null) {
                    return;
                }
                itemBinding.tabTitle.setTextColor(getResources().getColor(com.atmob.app.base.R.color.white50));
                itemBinding.tabTitle.setBackground(getResources().getDrawable(R.drawable.bg_voice_ai_tab_normal));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        voiceViewModel.setLastVoiceGenerateTxt(binding.etVoicePrint.getText() == null ? "" : binding.etVoicePrint.getText().toString());
    }

    @Override
    public void onStop() {
        super.onStop();
        if (player != null) {
            player.stop();
            voiceViewModel.setVoicePlayEnd();
        }
        voiceViewModel.setLastVoiceGenerateTxt(binding.etVoicePrint.getText() == null ? "" : binding.etVoicePrint.getText().toString());
    }


    @Override
    protected void initViewModel() {
        super.initViewModel();
        voiceViewModel = getViewModelProvider().get(VoiceAIViewModel.class);
        binding.setVoiceAIViewModel(voiceViewModel);
    }

    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        super.configImmersion(immersionBar);
        immersionBar.statusBarDarkFont(false);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player.release();
        }
    }
}
