package com.sound.prankparty.SecondFragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
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.ImageView;
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.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.sound.prankparty.FirstFragment.PlaySoundActivity;
import com.sound.prankparty.R;
import com.sound.prankparty.Room.AppDatabase;
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 java.io.IOException;
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 RecyclerView recyclerView;
    private RadioRecyclerViewAdapter radioRecyclerViewAdapter;
    private ImageView add;
    private ImageView backgroundTitle;
    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) {
        // 初始化视图
        View view = inflater.inflate(R.layout.fragment_radio, container, false);

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

        // 初始化视图组件
        add = view.findViewById(R.id.fragment_radio_add);
        backgroundTitle = view.findViewById(R.id.empty_radio_image);
        recyclerView = view.findViewById(R.id.radio_recyclerview);

        // 设置RecyclerView的布局管理器
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));

        // 初始化适配器
        radioRecyclerViewAdapter = new RadioRecyclerViewAdapter(requireContext(), this, favoriteSoundsDao);
        recyclerView.setAdapter(radioRecyclerViewAdapter);

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

//        itemTouchHelper.setSwipeEnabled(false);


        // 设置添加按钮的点击事件
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomBottomSheetDialog();
            }
        });


        recyclerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSound();
            }
        });

        // 刷新数据
        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 -> {
            // 处理选项 1
            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对象
            bottomSheetDialog.dismiss();
        });

        // 设置选项2的点击事件
        dialogView.findViewById(R.id.option2).setOnClickListener(v -> {
            // 处理选项 2
            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_GET_CONTENT);
        intent.setType("audio/*");
        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);
                }
                String[] currentDateTime = getCurrentDateTime();

                long finalDuration = duration;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            saveSoundsDao.insertSound(new SaveSounds(fileName, audioUri.toString(), currentDateTime[0], currentDateTime[1], formatDuration(finalDuration)));
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 在主线程中显示错误信息
                            requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(requireContext(), "插入数据库失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        }
    }

    private void playSound(){

//        SoundItem soundItem = new SoundItem(audioUri.toString(),"https://resource-sg-public.lux-ad.com/prank/7f35214ab21c8edb7afd193442126aca.png","Baby Sneeze 1");

        String ine = "un";
        Log.d("dskod",ine);
        Intent intent = new Intent(requireActivity(), PlaySoundActivity.class);
//        intent.putExtra("1234", soundItem);
        requireActivity().startActivity(intent);

    }


    // 获取文件名
    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();
        retriever.setDataSource(requireContext(), uri);
        String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        retriever.release();
        return duration != null ? Long.parseLong(duration) : 0;
    }

    // 格式化时长
    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 static String[] getCurrentDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        Date now = new Date();
        String currentDate = dateFormat.format(now);
        String currentTime = timeFormat.format(now);
        return new String[]{currentDate, currentTime};
    }

    // 刷新数据
    public void refreshData() {
        new Thread(() -> {
            saveSoundsList = saveSoundsDao.getAllSounds();
            requireActivity().runOnUiThread(() -> {
                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) add.getLayoutParams();
                if (saveSoundsList.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    backgroundTitle.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 {
                    recyclerView.setVisibility(View.VISIBLE);
                    backgroundTitle.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;
                }

                add.setLayoutParams(layoutParams);
                radioRecyclerViewAdapter.updateData(saveSoundsList);
            });
        }).start();
    }
}
