package com.design.mischiefgo.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.GetContent
import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.design.mischiefgo.databinding.FragmentYellowStartBinding
import com.design.mischiefgo.ut.CommonUtil
import com.design.mischiefgo.ut.StartAndEndAdapter
import com.design.mischiefgo.entity.Duplicate
import com.design.mischiefgo.entity.MainViewModel
import com.design.mischiefgo.ut.OnMoreClickListener

class YellowStartFragment : Fragment(),OnMoreClickListener{
    private lateinit var binding: FragmentYellowStartBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter: StartAndEndAdapter
    private var permission_read_audio: Array<String> = arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
    private var permission_record_audio: String = Manifest.permission.RECORD_AUDIO
    private var permission_store: Array<String> = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private lateinit var requestStorePermissionsLauncher: ActivityResultLauncher<Array<String>>
    private lateinit var requestRecordAudioLauncher: ActivityResultLauncher<String>
    private lateinit var audioPickerLauncher: ActivityResultLauncher<String>
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        binding = FragmentYellowStartBinding.inflate(inflater, container, false)
        viewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        initView()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        viewModel.loadCustomItems()
    }
    private fun initView() {
        adapter = StartAndEndAdapter()
        adapter.setListener(this)
        viewModel.customItems.observe(viewLifecycleOwner){customList ->
            Log.d("CustomFragment", "initView: $customList")
            if(customList.isEmpty()){
                binding.emptyView.visibility=View.VISIBLE
                binding.recyclerView.visibility=View.GONE
            }else{
                binding.emptyView.visibility=View.GONE
                binding.recyclerView.visibility=View.VISIBLE
                adapter.setList(customList,1)
                adapter.notifyDataSetChanged()
            }
        }
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager=
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL,false)
        binding.recordImg.setOnClickListener {
            selectBtnClick(1)
        }
        binding.diyImg.setOnClickListener {
            selectBtnClick(0)
        }
        requestRecordAudioLauncher = registerForActivityResult<String, Boolean>(
            RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                intentRecordAudio()
            } else {
                Toast.makeText(requireContext(), "Recording permission denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }

        requestStorePermissionsLauncher =
            registerForActivityResult<Array<String>, Map<String, Boolean>>(
                RequestMultiplePermissions()
            ) { result ->
                var isGranted = true
                for ((_, value) in result) {
                    isGranted = value
                    if (!value) {
                        isGranted = false
                    }
                }
                if (isGranted) {
                    importFromLocal()
                } else {
                    Toast.makeText(requireContext(), " permits denied", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        audioPickerLauncher = registerForActivityResult<String, Uri>(
            GetContent()
        ) { uri -> // Handle the returned Uri

            if (uri != null) {
                Log.d("---------", "========uri=$uri")
                val duration: Long = CommonUtil.getAudioDuration(requireContext(), uri)
                val intent = Intent(
                    requireContext(),
                    SaveToLocalActivity::class.java
                )
                intent.putExtra(SaveToLocalActivity.KEY_Path, uri.toString())
                intent.putExtra(SaveToLocalActivity.KEY_Time, duration)
                startActivity(intent)
            }
        }
    }

    override fun onMoreClick(duplicate: Duplicate) {
        viewModel.deleteItem(duplicate)
    }

    fun selectBtnClick(type: Int) {
        if(type == 0){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        requireContext(),
                        permission_read_audio[0]
                    )
                    != PackageManager.PERMISSION_GRANTED
                ) {
                    requestStorePermissionsLauncher.launch(permission_read_audio)
                    //                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_read_audio,
//                            ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                } else {
                    importFromLocal()
                }
            } else {
                if ((ContextCompat.checkSelfPermission(
                        requireContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                            != PackageManager.PERMISSION_GRANTED) ||
                    (ContextCompat.checkSelfPermission(
                        requireContext(),
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                            != PackageManager.PERMISSION_GRANTED)
                ) {
                    requestStorePermissionsLauncher.launch(permission_store)
                    //                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_store, ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                } else {
                    importFromLocal()
                }
            }
        }
        else{
            checkAndRequestAudioPermission()
        }
    }
    private fun importFromLocal() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.setType("audio/*")
        audioPickerLauncher.launch("audio/*")
    }
    private fun checkAndRequestAudioPermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), permission_record_audio)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestRecordAudioLauncher.launch(permission_record_audio)
        } else {
            intentRecordAudio()
        }
    }
    private fun intentRecordAudio() {
        val intent = Intent(requireContext(), ListenSoundActivity::class.java)
        startActivity(intent)
    }
}