package xn.xxp.main.monitor;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;

import cn.nodemedia.NodePlayer;
import cn.nodemedia.NodePlayerDelegate;
import cn.nodemedia.NodePlayerView;

import core.util.FastClickDelegate;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import xn.xxp.R;

public class MonitorDialog extends Dialog {

    private final MonitorInfo monitorInfo;
    private NodePlayer nodePlayer;
    private TextView textView;
    private TextView loadingText;
    private ProgressBar loadingProgress;
    private NodePlayerView nodePlayerView;
    private boolean isUsingOriginalPlayer = false;

    public MonitorDialog(@NonNull Context context, MonitorInfo monitorInfo, OnDismissListener dismissListener) {
        super(context, R.style.FullScreenDialog);
        this.monitorInfo = monitorInfo;
        setOnDismissListener(dismissListener);

        // 设置对话框为全屏
        if (getWindow() != null) {
            getWindow().setFlags(
                    android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN
            );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_monitor);

        // 设置窗口动画
        Window window = getWindow();
        if (window != null) {
            window.setWindowAnimations(R.style.DialogAnimation);
            window.setLayout(
                    android.view.WindowManager.LayoutParams.MATCH_PARENT,
                    android.view.WindowManager.LayoutParams.MATCH_PARENT
            );
        }

        initVideoPlayer();
    }

    private void initVideoPlayer() {
        LogUtils.d("初始化全屏播放器 - 复用原始播放器");

        // 获取返回按钮
        textView = findViewById(R.id.back);
        if (textView == null) {
            LogUtils.e("找不到返回按钮");
            return;
        }

        // 设置返回按钮点击事件
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d("点击返回按钮");
                textView.setText("正在退出...");
                dismiss();
            }
        });

        // 获取布局中的TextureView
        View oldTextureView = findViewById(R.id.textureView);
        if (oldTextureView == null) {
            LogUtils.e("找不到textureView");
            return;
        }

        // 获取父布局
        android.view.ViewGroup parent = (android.view.ViewGroup) oldTextureView.getParent();
        if (parent == null) {
            LogUtils.e("textureView没有父布局");
            return;
        }

        // 创建NodePlayerView（用于全屏显示）
        nodePlayerView = new NodePlayerView(getContext());
        android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT
        );
        nodePlayerView.setLayoutParams(params);
        nodePlayerView.setKeepScreenOn(true);

        // 替换原TextureView
        int index = parent.indexOfChild(oldTextureView);
        parent.removeView(oldTextureView);
        parent.addView(nodePlayerView, index);

        LogUtils.d("NodePlayerView已添加到布局");

        // 获取原始播放器
        nodePlayer = monitorInfo.getNodePlayer();
        if (nodePlayer == null) {
            LogUtils.e("原始播放器为空，创建新的");
            createNewPlayer();
        } else {
            // === 关键优化：复用原始播放器 ===
            reuseOriginalPlayer();
        }
    }

    /**
     * 复用原始播放器（0延迟）
     */
    private void reuseOriginalPlayer() {
        LogUtils.d("复用原始播放器 - 立即显示");
        isUsingOriginalPlayer = true;

        try {
            // 1. 立即设置新的播放器视图
            nodePlayer.setPlayerView(nodePlayerView);
            LogUtils.d("已切换播放器视图到全屏");

            // 2. 如果播放器是暂停状态，恢复播放
            nodePlayer.start();

            // 3. 立即显示（不需要等待缓冲）
            showImmediately();

            // 4. 添加监听器（可选）
            nodePlayer.setNodePlayerDelegate(new NodePlayerDelegate() {
                @Override
                public void onEventCallback(NodePlayer player, int event, String msg) {
                    {
                        if (event == 1000 || event == 1001 || event == 2000 || event == 2001) {
                            LogUtils.d("全屏播放器开始播放");
                            hideLoadingImmediately();
                        } else if (event == 1003 || event == 2003) {
                            LogUtils.e("全屏播放失败: " + msg);
                        }
                    }
                }
            });

        } catch (Exception e) {
            LogUtils.e("复用播放器失败: " + e.getMessage());
            // 失败时创建新播放器
            createNewPlayer();
        }
    }

    /**
     * 立即显示（隐藏loading）
     */
    private void showImmediately() {
        // 不需要loading，因为视频已经在播放
        if (loadingText != null) {
            loadingText.setVisibility(View.GONE);
        }
        if (loadingProgress != null) {
            loadingProgress.setVisibility(View.GONE);
        }
        LogUtils.d("立即显示视频画面");
    }

    /**
     * 创建新的播放器（备用方案）
     */
    private void createNewPlayer() {
        LogUtils.d("创建新的全屏播放器");
        isUsingOriginalPlayer = false;

        // 显示加载提示
        setupLoadingView();

        ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                try {
                    // 检查流地址
                    if (monitorInfo == null || monitorInfo.getMonitorVo() == null) {
                        LogUtils.e("监控信息为空");
                        hideLoading();
                        return null;
                    }

                    String streamUrl = monitorInfo.getMonitorVo().streamUrl;
                    if (streamUrl == null || streamUrl.isEmpty()) {
                        LogUtils.e("流地址为空");
                        hideLoading();
                        return null;
                    }

                    LogUtils.d("创建新播放器，流地址: " + streamUrl);

                    // 创建新的NodePlayer
                    nodePlayer = new NodePlayer(getContext());

                    // 设置播放视图
                    if (nodePlayerView != null) {
                        nodePlayer.setPlayerView(nodePlayerView);
                    }

                    // 快速配置
                    nodePlayer.setRtspTransport("1");
                    nodePlayer.setVideoEnable(true);
                    nodePlayer.setAudioEnable(false);

                    // 使用稍大的缓冲（200ms），保证快速连接
                    try {
                        nodePlayer.setBufferTime(200);
                        nodePlayer.setMaxBufferTime(600);
                    } catch (Exception e) {
                        // 忽略
                    }

                    // 硬件解码
                    try {
                        java.lang.reflect.Method setHWEnableMethod = nodePlayer.getClass()
                                .getMethod("setHWEnable", boolean.class);
                        setHWEnableMethod.invoke(nodePlayer, true);
                    } catch (Exception e) {
                        // 忽略
                    }

                    // 使用子码流（如果可用）
                    String optimizedUrl = streamUrl;
                    if (streamUrl.contains("stream=0")) {
                        optimizedUrl = streamUrl.replace("stream=0", "stream=1");
                    } else if (streamUrl.contains("main")) {
                        optimizedUrl = streamUrl.replace("main", "sub");
                    }

                    // 设置地址并启动
                    nodePlayer.setInputUrl(optimizedUrl);
                    nodePlayer.start();

                    // 添加监听器
                    nodePlayer.setNodePlayerDelegate(new NodePlayerDelegate() {
                        @Override
                        public void onEventCallback(NodePlayer player, int event, String msg) {
                            {
                                if (event == 1000 || event == 1001 || event == 2000 || event == 2001) {
                                    LogUtils.d("新播放器开始播放");
                                    // 1秒后隐藏loading（给缓冲时间）
                                    ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            hideLoading();
                                        }
                                    }, 1000);
                                }
                            }
                        }
                    });

                    // 3秒超时强制隐藏loading
                    ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                        @Override
                        public void run() {
                            hideLoading();
                        }
                    }, 3000);

                } catch (Exception e) {
                    LogUtils.e("创建播放器失败: " + e.getMessage());
                    hideLoadingWithError("播放失败");
                }
                return null;
            }

            @Override
            public void onSuccess(Object result) {
                LogUtils.d("创建播放器成功");
            }
        });
    }

    private void setupLoadingView() {
        // 创建加载视图（与之前类似但简化）
        if (loadingText == null) {
            loadingText = new TextView(getContext());
            android.widget.RelativeLayout.LayoutParams textParams = new android.widget.RelativeLayout.LayoutParams(
                    android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
                    android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT
            );
            textParams.addRule(android.widget.RelativeLayout.CENTER_IN_PARENT);
            loadingText.setLayoutParams(textParams);
            loadingText.setText("加载中...");
            loadingText.setTextColor(0xFFFFFFFF);
            loadingText.setTextSize(14);
            loadingText.setVisibility(View.VISIBLE);

            if (nodePlayerView != null && nodePlayerView.getParent() != null) {
                ((android.view.ViewGroup) nodePlayerView.getParent()).addView(loadingText);
            }
        }
    }

    private void hideLoadingImmediately() {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loadingText != null) {
                    loadingText.setVisibility(View.GONE);
                }
                if (loadingProgress != null) {
                    loadingProgress.setVisibility(View.GONE);
                }
            }
        });
    }

    private void hideLoading() {
        hideLoadingImmediately();
    }

    private void hideLoadingWithError(String error) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loadingText != null) {
                    loadingText.setText(error);
                    // 3秒后隐藏
                    ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (loadingText != null) {
                                loadingText.setVisibility(View.GONE);
                            }
                        }
                    }, 3000);
                }
            }
        });
    }

    @Override
    public void dismiss() {
        LogUtils.d("Dialog dismiss - 恢复小窗口播放");

        // === 关键修复：先恢复原始视图，再清理Dialog ===
        if (isUsingOriginalPlayer && nodePlayer != null && monitorInfo != null) {
            try {
                // 1. 先暂停播放（避免切换时的闪烁）
                nodePlayer.pause();

                // 2. 切换到原始视图
                NodePlayerView originalView = monitorInfo.getNodePlayerView();
                if (originalView != null && originalView.getParent() != null) {
                    nodePlayer.setPlayerView(originalView);
                    LogUtils.d("已恢复小窗口视图");
                } else {
                    LogUtils.e("原始视图无效或已被移除");
                }

                // 3. 重新开始播放（在原始视图中）
                ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            nodePlayer.start();
                        } catch (Exception e) {
                            LogUtils.e("恢复播放失败: " + e.getMessage());
                        }
                    }
                }, 100);

            } catch (Exception e) {
                LogUtils.e("恢复小窗口失败: " + e.getMessage());
            }
        }

        // === 关键：不要释放播放器！只是清理Dialog的资源 ===
        if (!isUsingOriginalPlayer && nodePlayer != null) {
            // 只释放新创建的播放器
            try {
                nodePlayer.stop();
                nodePlayer.release();
            } catch (Exception e) {
                LogUtils.e("释放新播放器失败: " + e.getMessage());
            }
        } else if (isUsingOriginalPlayer) {
            // === 关键：不要释放原始播放器！置空引用即可 ===
            nodePlayer = null;
        }

        // 清理Dialog的视图
        if (nodePlayerView != null && nodePlayerView.getParent() != null) {
            ((android.view.ViewGroup) nodePlayerView.getParent()).removeView(nodePlayerView);
        }

        // 清理加载视图
        if (loadingText != null && loadingText.getParent() != null) {
            ((android.view.ViewGroup) loadingText.getParent()).removeView(loadingText);
        }
        if (loadingProgress != null && loadingProgress.getParent() != null) {
            ((android.view.ViewGroup) loadingProgress.getParent()).removeView(loadingProgress);
        }

        // 清理引用
        nodePlayerView = null;
        loadingText = null;
        loadingProgress = null;

        // 最后调用父类的dismiss
        try {
            super.dismiss();
        } catch (Exception e) {
            LogUtils.e("super.dismiss()失败: " + e.getMessage());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 只暂停新创建的播放器，复用播放器不处理
        if (!isUsingOriginalPlayer && nodePlayer != null) {
            try {
                nodePlayer.pause();
            } catch (Exception e) {
                // 忽略
            }
        }
    }
}