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

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.UriPermission;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.offline.music.player.R;
import com.offline.music.player.adapter.A_ImportFragmentAdapter;
import com.offline.music.player.databinding.FragmentAImportBinding;
import com.offline.music.player.javabean.A_data.AudioItem;
import com.offline.music.player.ui.activity.A_SettingActivity;
import com.offline.music.player.ui.fragmnt.viewmodel.A_VMImport;

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

public class A_ImportFragment extends BaseFragment<FragmentAImportBinding> {

    private static final int REQUEST_CODE_READ_MEDIA_AUDIO = 1001;
    private static final int REQUEST_CODE_PICK_AUDIO = 1002;

    private A_ImportFragmentAdapter adapter;
    private A_VMImport viewModel;

    private String newName = "";

    @Override
    protected FragmentAImportBinding getFragmentVb() {
        return FragmentAImportBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        viewModel = new ViewModelProvider(this).get(A_VMImport.class);
        adapter = new A_ImportFragmentAdapter(requireActivity(),newName);

        setupRecyclerView();
//        observeAudioFiles();
        initEvent();
    }

    private void setupRecyclerView() {
        Vb.importRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        Vb.importRecycler.setAdapter(adapter);
    }

    private void observeAudioFiles() {
        viewModel.getAudioFiles().observe(getViewLifecycleOwner(), this::updateAudioList);
    }

    private void updateAudioList(List<AudioItem> audioFiles) {
        adapter.setAudioFiles(audioFiles);
        // 每次更新音频列表时，重新持久化权限
        for (AudioItem item : audioFiles) {
            Uri audioUri = Uri.parse(item.getFile());
            checkPersistableUriPermission(audioUri);
        }
    }

    private void initEvent() {
        // 确保只设置一次点击事件
        Vb.setting.setOnClickListener(v -> startActivity(new Intent(getContext(), A_SettingActivity.class)));
        Vb.add.setOnClickListener(v -> {
            Log.d("A_ImportFragment", "Add button clicked"); // 添加调试日志
            checkAndOpenAudioPicker();
        });
        adapter.setOnOptionClickListener(this::showPopupWindow);
    }


    private void showPopupWindow(int position, String filePath, View anchorView) {
        // 膨胀 PopupWindow 的布局
        View popupView = LayoutInflater.from(requireContext()).inflate(R.layout.options_popup_window, null);

        // 创建 PopupWindow
        PopupWindow popupWindow = new PopupWindow(popupView,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                true);

        // 设置背景为透明
        popupWindow.setOutsideTouchable(true);  // 允许点击外部关闭

        // 获取 PopupWindow 中的控件
        Button renameButton = popupView.findViewById(R.id.rename);
        Button deleteButton = popupView.findViewById(R.id.delete);

        // 设置重命名按钮的点击事件
        renameButton.setOnClickListener(v -> {
            popupWindow.dismiss();
            showRenameDialog(position);
        });

        // 设置删除按钮的点击事件
        deleteButton.setOnClickListener(v -> {
            deleteAudioFile(position, filePath, popupWindow);
        });

        // 显示 PopupWindow，设置其位置
        popupWindow.showAsDropDown(anchorView, 0, 10);  // 在 anchorView 下方显示
    }

    private void showRenameDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.rename_dialog, null);
        builder.setView(dialogView);

        AlertDialog subDialog = builder.create();
        Objects.requireNonNull(subDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        EditText inputField = dialogView.findViewById(R.id.input_field);
        TextView cancel = dialogView.findViewById(R.id.cancel);
        TextView confirm = dialogView.findViewById(R.id.confirm);

        confirm.setOnClickListener(view -> {
            String newName = inputField.getText().toString();
            adapter.updateTitle(position, newName); // 更新 UI

            // 获取音频文件路径并更新名称
            String filePath = adapter.getAudioFile(position).getFile(); // 获取音频文件路径
            viewModel.updateAudioFileName(filePath, newName); // 更新 ViewModel 中的名称

            subDialog.dismiss();
        });

        cancel.setOnClickListener(view -> subDialog.dismiss());

        subDialog.show();
    }

    private void deleteAudioFile(int position, String filePath, PopupWindow popupWindow) {
        viewModel.markAudioAsDeleted(filePath);
//        Toast.makeText(requireContext(), "删除按钮被点击, 项目: " + position, Toast.LENGTH_SHORT).show();
        popupWindow.dismiss();
    }

    private void checkAndOpenAudioPicker() {
        Log.d("A_ImportFragment", "checkAndOpenAudioPicker called"); // 添加调试日志
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(Manifest.permission.READ_MEDIA_AUDIO);
                Log.d("A_ImportFragment", "123Build.VERSION_CODES.TIRAMISU"); // 添加调试日志
            } else {
                openAudioPicker();
                Log.d("A_ImportFragment", "Build.VERSION_CODES.TIRAMISU"); // 添加调试日志
            }
        } else {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(Manifest.permission.READ_EXTERNAL_STORAGE);
                Log.d("A_ImportFragment", "156Build.VERSION_CODES.TIRAMISU"); // 添加调试日志
                showPermissionDeniedDialog();
            } else {
                openAudioPicker();
                Log.d("A_ImportFragment", "Not Build.VERSION_CODES.TIRAMISU"); // 添加调试日志
            }
        }
    }

    private void showPermissionDeniedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("Permission denied");
        builder.setMessage("You have denied permission to read the audio file, and some functions will not work properly. Please go to Application Settings to grant permissions.");
        builder.setPositiveButton("Go to Settings", (dialog, which) -> {
            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        });
        builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
        builder.show();
    }

    private void requestPermissions(String permission) {
        ActivityCompat.requestPermissions(requireActivity(), new String[]{permission}, REQUEST_CODE_READ_MEDIA_AUDIO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_READ_MEDIA_AUDIO) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("A_ImportFragment", "Permission granted");
                openAudioPicker();
            } else {
                Toast.makeText(requireContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void openAudioPicker() {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(getContext(), "The external storage is unavailable", Toast.LENGTH_LONG).show();
            return;
        }

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, REQUEST_CODE_PICK_AUDIO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_AUDIO && resultCode == RESULT_OK && data != null) {
            Uri selectedAudioUri = data.getData();
            if (selectedAudioUri != null) {
                // 持久化 URI 访问权限
                requireActivity().getContentResolver().takePersistableUriPermission(
                        selectedAudioUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

                try {
                    viewModel.addAudioFile(selectedAudioUri);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 检查所有音频文件的持久化权限
        for (AudioItem item : adapter.getAudioFiles()) {
            Uri audioUri = Uri.parse(item.getFile());
            checkPersistableUriPermission(audioUri);
        }
        observeAudioFiles();
    }

    // 检查并持久化权限
    private void checkPersistableUriPermission(Uri uri) {
        boolean hasPermission = false;
        for (UriPermission permission : requireContext().getContentResolver().getPersistedUriPermissions()) {
            if (permission.getUri().equals(uri) && permission.isReadPermission()) {
                hasPermission = true;
                break;
            }
        }

        if (!hasPermission) {
            requireContext().getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
    }
}
