package com.all.pdfreader.pro.app.ui.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.graphics.drawable.toDrawable
import androidx.core.net.toUri
import androidx.fragment.app.DialogFragment
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogPermissionBinding
import com.all.pdfreader.pro.app.sp.AppStore
import com.all.pdfreader.pro.app.util.StoragePermissionHelper
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class PermissionDialogFragment : BottomSheetDialogFragment() {

    private lateinit var binding: DialogPermissionBinding

    private val multiplePermissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            val allGranted = permissions.values.all { it }
            if (allGranted) {
                onPermissionGranted()
            } else {
                showPermissionDeniedDialog()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DialogPermissionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            ?.setBackgroundResource(R.drawable.dr_rc_top_12_bg_white)
        // 设置对话框在底部显示并左右铺满
        dialog?.window?.let { window ->
            window.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            window.setGravity(Gravity.BOTTOM)
            window.setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
        }
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        AppStore(requireActivity()).isShowPermissionsDialogPrompt = true

        binding.prDesc.text =
            getString(R.string.permission_required_desc_1, getString(R.string.app_name))

        binding.allowAccessBtn.setOnClickListener {
            if (checkPermissions()) {
                onPermissionGranted()
            } else {
                requestPermissions()
            }
            dismiss()
        }

        binding.closeBtn.setOnClickListener {
            dismiss()
            (activity as? CloseCallback)?.onClose()
        }
    }

    private fun checkPermissions(): Boolean {
        return StoragePermissionHelper.hasBasicStoragePermission(requireContext())
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            StoragePermissionHelper.openAllFilesAccessSettings(requireContext() as Activity)
        } else {
            val permissions = StoragePermissionHelper.getRequiredPermissions()
            multiplePermissionsLauncher.launch(permissions)
        }
    }

    private fun showPermissionDeniedDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle(getString(R.string.permission_denied))
            .setMessage(getString(R.string.pd_content_notice))
            .setPositiveButton(getString(R.string.go)) { _, _ ->
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = "package:${requireContext().packageName}".toUri()
                startActivity(intent)
                dismiss()
            }
            .setNegativeButton(getString(R.string.exit)) { _, _ ->
                dismiss()
            }
            .setCancelable(false)
            .show()
    }

    //有权限直接响应授权成功
    private fun onPermissionGranted() {
        dismiss()
        (activity as? PermissionCallback)?.onPermissionGranted()
    }

    interface PermissionCallback {
        fun onPermissionGranted()
    }

    interface CloseCallback {
        fun onClose()
    }
}