package com.offline.music.task.player.ui.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ktx.immersionBar
import com.offline.music.task.player.ProApp
import com.offline.music.task.player.R
import com.offline.music.task.player.databinding.FragmentMeBinding
import com.offline.music.task.player.db.bean.Audio
import com.offline.music.task.player.ui.adapter.MeLocalSongAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MeFragment : Fragment() {
    private lateinit var binding: FragmentMeBinding
    private var meLocalSongAdapter: MeLocalSongAdapter? = null
    private var importAdapterList: MutableList<Audio> = mutableListOf()
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentMeBinding.inflate(layoutInflater)
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        binding.addBtn.setOnClickListener {
            binding.addBtn.visibility = View.GONE
            checkAndRequestPermissions()
        }
        importAdapterList.clear()
        importAdapterList.addAll(ProApp.importList)
        meLocalSongAdapter = MeLocalSongAdapter(requireActivity(), importAdapterList)
        binding.importRv.layoutManager =
            LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
        binding.importRv.adapter = meLocalSongAdapter
    }

    private var requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                openAudioPicker()
            } else {
                showExplanationDialog()
            }
        }

    private fun openAudioPicker() {
        binding.loadingLayout.visibility = View.VISIBLE
        getMusicFiles(requireActivity())
    }

    private fun showExplanationDialog() {
        AlertDialog.Builder(requireActivity())
            .setTitle(getString(R.string.permission_request))
            .setMessage(getString(R.string.permission_request_desc))
            .setPositiveButton(getString(R.string.ok)) { dialog, which ->
                requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
                dialog.dismiss()
            }
            .setNegativeButton(getString(R.string.cancel)) { dialog, which ->
                dialog.dismiss()
            }
            .show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onResume() {
        super.onResume()
        initImmersionBar()

        if (importAdapterList.isNotEmpty()) {
            binding.noContentLayout.visibility = View.GONE
        } else {
            binding.noContentLayout.visibility = View.VISIBLE
        }

        if (ProApp.currentPlayingAudio != null) {
            if (ProApp.importList.isNotEmpty()) {
                importAdapterList.clear()
                importAdapterList.addAll(ProApp.importList)
                for ((index, audio) in importAdapterList.withIndex()) {
                    if (audio.file == ProApp.currentPlayingAudio?.file) {
                        meLocalSongAdapter?.notifyDataSetChanged()
                        break
                    }
                }
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            initImmersionBar()
        }
    }

    private fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(false)
            statusBarView(binding.view)
        }
    }

    private fun getAudioDuration(uri: Uri): Long {
        var duration = 0L
        try {
            val mediaPlayer = MediaPlayer.create(requireContext(), uri)
            duration = mediaPlayer.duration.toLong()
            mediaPlayer.release()
            return duration
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return duration
    }

    @SuppressLint("NotifyDataSetChanged")
    fun getMusicFiles(context: Context): List<String> {
        val musicFiles = mutableListOf<String>()
        val contentResolver: ContentResolver = context.contentResolver

        // 定义查询参数
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DISPLAY_NAME,
            MediaStore.Audio.Media.DATA
        )

        val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0"
        val sortOrder = "${MediaStore.Audio.Media.DISPLAY_NAME} ASC"

        // 查询音频文件
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            sortOrder
        )

        cursor?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)
            val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)

            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val name = cursor.getString(nameColumn)
                val data = cursor.getString(dataColumn)
                val contentUri = ContentUris.withAppendedId(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    id
                )
                val duration2 = getAudioDuration(contentUri)
                val audio = Audio(name, contentUri.toString(), "", duration2, false)

                musicFiles.add(contentUri.toString())
                // 如果你想要获取文件的具体路径，可以使用 data 变量
                // musicFiles.add(data)

                CoroutineScope(Dispatchers.IO).launch {
                    if (audio.duration > 0) {
                        ProApp.databaseManager.insertAudioFile(audio)
                    }
                    withContext(Dispatchers.Main) {
                        ProApp.initImportAudio {
                            importAdapterList.clear()
                            importAdapterList.addAll(ProApp.importList)
                            meLocalSongAdapter?.notifyDataSetChanged()
                            if (importAdapterList.isNotEmpty()) {
                                binding.noContentLayout.visibility = View.GONE
                            } else {
                                binding.noContentLayout.visibility = View.VISIBLE
                                showNoDataDialog()
                            }
                            binding.loadingLayout.visibility = View.GONE
                        }
                    }
                }
            }
        }
        return musicFiles
    }

    private fun showNoDataDialog() {
        AlertDialog.Builder(requireActivity())
            .setTitle(getString(R.string.prompt))
            .setMessage(getString(R.string.no_data_prompt_dialog_content))
            .setPositiveButton(getString(R.string.ok)) { dialog, _ ->
                binding.addBtn.visibility = View.VISIBLE
                dialog.dismiss()
            }
            .setCancelable(false)
            .show()
    }


    private fun checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val permissionsToRequest = mutableListOf<String>()

            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.READ_MEDIA_IMAGES
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.READ_MEDIA_VIDEO
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_VIDEO)
            }
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.READ_MEDIA_AUDIO
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_AUDIO)
            }

            if (permissionsToRequest.isNotEmpty()) {
                requestMultiplePermissionsLauncher.launch(permissionsToRequest.toTypedArray())
            } else {
                openAudioPicker()
            }
        } else {
            // 请求旧版本的权限
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            } else {
                openAudioPicker()
            }
        }
    }

    private val requestMultiplePermissionsLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        permissions.forEach { (permission, isGranted) ->
            if (isGranted) {
                openAudioPicker()
            } else {
                showExplanationDialog()
            }
        }
    }

}