package com.sound.prankparty.Fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sound.prankparty.Activity.NewRecordActivity;
import com.sound.prankparty.Adapter.RadioRecyclerViewAdapter;
import com.sound.prankparty.R;
import com.sound.prankparty.Room.AppDatabase;
import com.sound.prankparty.Room.FavoriteSounds;
import com.sound.prankparty.Room.FavoriteSoundsDao;
import com.sound.prankparty.Room.SaveSounds;
import com.sound.prankparty.Room.SaveSoundsDao;
import com.sound.prankparty.Utils.MyItemTouchHelperCallback;
import com.sound.prankparty.databinding.FragmentRadioBinding;

import java.io.File;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class RadioFragment extends Fragment {

    private FragmentRadioBinding binding;
    private RadioRecyclerViewAdapter radioRecyclerViewAdapter;
    private SaveSoundsDao saveSoundsDao;
    private MyItemTouchHelperCallback myItemTouchHelperCallback;
    private ItemTouchHelper itemTouchHelper;
    private Uri audioUri;
    private String fileName;
    private AppDatabase appDatabase;
    private FavoriteSoundsDao favoriteSoundsDao;
    private List<SaveSounds> saveSoundsList;
    private static final int REQUEST_CODE_READ_MEDIA_AUDIO = 1001;
    private static final int REQUEST_CODE_PICK_AUDIO = 1002;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 使用 ViewBinding 初始化视图
        binding = FragmentRadioBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        // 初始化数据库
        appDatabase = AppDatabase.getDatabase(requireContext());
        saveSoundsDao = appDatabase.saveSoundsDao();
        favoriteSoundsDao = appDatabase.favoriteSoundsDao();

        // 初始化 RecyclerView
        binding.radioRecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 1));
        radioRecyclerViewAdapter = new RadioRecyclerViewAdapter(requireContext(), this, favoriteSoundsDao, saveSoundsDao);
        binding.radioRecyclerview.setAdapter(radioRecyclerViewAdapter);

        // 初始化 MyItemTouchHelperCallback
        myItemTouchHelperCallback = new MyItemTouchHelperCallback(this);
        itemTouchHelper = new ItemTouchHelper(myItemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(binding.radioRecyclerview);

        // 设置添加按钮的点击事件
        binding.fragmentRadioAdd.setOnClickListener(v -> showCustomBottomSheetDialog());

        // 刷新数据
        refreshData();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    private void showCustomBottomSheetDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.bottom_sheet_dialog, null);

        bottomSheetDialog.setCanceledOnTouchOutside(false);

        // 设置选项1的点击事件
        dialogView.findViewById(R.id.option1).setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                openAudioPicker();
            } else {
                if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(),
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            REQUEST_CODE_READ_MEDIA_AUDIO);
                } else {
                    openAudioPicker();
                }
            }
            bottomSheetDialog.dismiss();
        });

        // 设置选项2的点击事件
        dialogView.findViewById(R.id.option2).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), NewRecordActivity.class);
            startActivity(intent);
            bottomSheetDialog.dismiss();
        });

        // 设置取消按钮的点击事件
        dialogView.findViewById(R.id.cancel_button).setOnClickListener(v -> {
            bottomSheetDialog.dismiss();
        });

        bottomSheetDialog.setContentView(dialogView);
        bottomSheetDialog.show();
    }

    // 处理权限请求结果

    @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) {
                openAudioPicker();
            } else {
                Toast.makeText(requireContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
    // 打开音频选择器

    private void openAudioPicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); // 改为 ACTION_OPEN_DOCUMENT
        intent.setType("audio/*"); // 设置 MIME 类型为音频
        intent.addCategory(Intent.CATEGORY_OPENABLE); // 限制为可打开的文件
        startActivityForResult(intent, REQUEST_CODE_PICK_AUDIO);
    }

    // 处理 Activity 结果

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_AUDIO && resultCode == RESULT_OK) {
            if (data != null) {
                audioUri = data.getData();
                assert audioUri != null;
                fileName = getFileName(audioUri);
                long duration = 0;
                try {
                    duration = getAudioDuration(audioUri);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                // 获取文件的最后修改时间
                long lastModifiedTime = getLastModifiedTime(requireContext(), audioUri);
                String[] lastModifiedDateTime = getDateTimeFromLastModified(lastModifiedTime);

                long finalDuration = duration;

                new Thread(() -> {
                    try {
                        // 在插入数据库前检查该 URI 是否已经存在
                        int count = saveSoundsDao.countSoundsByUri(audioUri.toString());
                        if (count > 0) {
                            // 在主线程中显示文件已经存在的提示
                            requireActivity().runOnUiThread(() ->
                                    Toast.makeText(requireContext(), "该文件已经导入过，不能重复导入", Toast.LENGTH_LONG).show());
                        } else {
                            // 插入新记录
                            saveSoundsDao.insertSound(new SaveSounds(fileName, audioUri.toString(), lastModifiedDateTime[0], lastModifiedDateTime[1], formatDuration(finalDuration)));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 在主线程中显示错误信息
                        requireActivity().runOnUiThread(() ->
                                Toast.makeText(requireContext(), "插入数据库失败: " + e.getMessage(), Toast.LENGTH_LONG).show());
                    }
                }).start();
            }
        }
    }

    // 获取文件名

    private String getFileName(Uri uri) {
        String result = null;
        if (Objects.equals(uri.getScheme(), "content")) {
            try (Cursor cursor = requireActivity().getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int displayNameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
                    if (displayNameIndex != -1) {
                        result = cursor.getString(displayNameIndex);
                    }
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            assert result != null;
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }
    // 获取音频时长

    private long getAudioDuration(Uri uri) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(requireContext(), uri);
            String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            return duration != null ? Long.parseLong(duration) : 0;
        } catch (Exception e) {
            e.printStackTrace(); // 可以记录日志或进行其他异常处理
            return 0;
        } finally {
            retriever.release();
        }
    }
    // 格式化时长

    private String formatDuration(long duration) {
        long minutes = (duration / 1000) / 60;
        long seconds = (duration / 1000) % 60;
        return String.format(Locale.getDefault(), "%d:%02d", minutes, seconds);
    }
    //获取最后修改时间

    public long getLastModifiedTime(Context context, Uri uri) {
        long lastModifiedTime = 0;

        if (uri != null && "content".equals(uri.getScheme())) {
            DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);
            if (documentFile != null && documentFile.exists()) {
                lastModifiedTime = documentFile.lastModified();
            }
        } else if (uri != null && "file".equals(uri.getScheme())) {
            File file = new File(uri.getPath());
            if (file.exists()) {
                lastModifiedTime = file.lastModified();
            }
        }

        return lastModifiedTime;
    }

    public static String[] getDateTimeFromLastModified(long lastModifiedTime) {
        // 自定义DateFormatSymbols以使用小写的am和pm
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.ENGLISH);
        dfs.setAmPmStrings(new String[]{"am", "pm"});

        // 使用自定义的DateFormatSymbols创建SimpleDateFormat
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mma", Locale.ENGLISH);
        timeFormat.setDateFormatSymbols(dfs);

        // 将最后修改时间转换为Date对象
        Date lastModifiedDate = new Date(lastModifiedTime);
        String date = dateFormat.format(lastModifiedDate);
        String time = timeFormat.format(lastModifiedDate);

        // 返回日期和时间字符串
        return new String[]{date, time};
    }

    public void deleteItem(int position) {
        new Thread(() -> {
            // 获取要删除的音频对象
            SaveSounds sound = saveSoundsList.get(position);
            String filePath = sound.getPath();

            // 删除数据库中的收藏记录
            FavoriteSounds favoriteSound = favoriteSoundsDao.getByPath(filePath);
            if (favoriteSound != null) {
                favoriteSoundsDao.delete(favoriteSound);
            }

            // 删除数据库中的音频记录
            saveSoundsDao.deleteSound(sound);

            // 删除文件系统中的实际录音文件
            File file = new File(filePath);
            if (file.exists()) {
                boolean deleted = file.delete();
                if (deleted) {
                    // 如果文件成功删除，可以在这里执行其他操作，比如记录日志
                    Log.d("DeleteItem", "录音文件已删除: " + filePath);
                } else {
                    // 如果文件删除失败，可以在这里处理
                    Log.e("DeleteItem", "删除录音文件失败: " + filePath);
                }
            } else {
                // 如果文件不存在，可以在这里处理
                Log.w("DeleteItem", "录音文件不存在: " + filePath);
            }

            // 在主线程中刷新UI
            requireActivity().runOnUiThread(this::refreshData);
        }).start();
    }

    // 刷新数据
    public void refreshData() {
        new Thread(() -> {
            saveSoundsList = saveSoundsDao.getAllSounds();
            requireActivity().runOnUiThread(() -> {
                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) binding.fragmentRadioAdd.getLayoutParams();
                if (saveSoundsList.isEmpty()) {
                    binding.radioRecyclerview.setVisibility(View.GONE);
                    binding.emptyRadioImage.setVisibility(View.VISIBLE);

                    // 清除与底部对齐的约束
                    layoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
                    layoutParams.bottomToTop = ConstraintLayout.LayoutParams.UNSET;

                    // 将 add 移动到屏幕中央
                    layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                } else {
                    binding.radioRecyclerview.setVisibility(View.VISIBLE);
                    binding.emptyRadioImage.setVisibility(View.GONE);

                    // 清除与中央对齐的约束
                    layoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
                    layoutParams.bottomToTop = ConstraintLayout.LayoutParams.UNSET;

                    // 将 add 移动到屏幕底部
                    layoutParams.topToBottom = R.id.radio_recyclerview;
                    layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                    layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
                }

                binding.fragmentRadioAdd.setLayoutParams(layoutParams);
                radioRecyclerViewAdapter.updateData(saveSoundsList);
            });
        }).start();
    }
}

