package com.ray650128.floatingwindow.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.AdapterView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.ray650128.floatingwindow.databinding.ActivitySettingBinding
import com.ray650128.floatingwindow.dp
import com.ray650128.floatingwindow.utils.DensityUtil
import com.ray650128.floatingwindow.utils.FloatingWindowHelperUtils
import com.ray650128.floatingwindow.utils.PreferenceUtil
import com.ray650128.floatingwindow.view.ValueEditor
import java.io.File


class SettingActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySettingBinding

    private var xOffset = 0
    private var yOffset = 0

    private var windowGravity = FloatingWindowHelperUtils.GravityType.TOP_LEFT

    private var windowIcon = FloatingWindowHelperUtils.IconType.CHICKEN

    private val requestPermission =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            permissions.entries.forEach {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                    if (it.key == Manifest.permission.READ_EXTERNAL_STORAGE && it.value) {
                        pickImage()
                    }
                } else {
                    if (it.key == Manifest.permission.READ_MEDIA_IMAGES && it.value) {
                        pickImage()
                    }
                }
                Log.e("DEBUG", "${it.key} = ${it.value}")
            }
        }

    private val galleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            val returnUri = data?.data ?: return@registerForActivityResult
            imageUri = saveImageToCache(returnUri)
            Log.d(TAG, "imageUri=$imageUri")
            val bitmap = BitmapFactory.decodeFile(imageUri)
            binding.imgPreview.setImageBitmap(bitmap)
            FloatingWindowHelperUtils.setIcon(windowIcon, imageUri)
            //workingCheckItemAdapter.setImageUri(currentPosition, currentUri)
            //checkPassButton()
        }
    }

    private var imageUri: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
        binding = ActivitySettingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        xOffset = PreferenceUtil.xOffset
        yOffset = PreferenceUtil.yOffset
        windowGravity = FloatingWindowHelperUtils.GravityType.fromInt(PreferenceUtil.gravity)
        windowIcon = FloatingWindowHelperUtils.IconType.fromInt(PreferenceUtil.icon)
        if (!PreferenceUtil.iconPath.isNullOrEmpty()) {
            imageUri = PreferenceUtil.iconPath
        }

        binding.apply {
            spGravity.apply {
                setSelection(PreferenceUtil.gravity)
                onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        windowGravity = FloatingWindowHelperUtils.GravityType.fromInt(position)
                        FloatingWindowHelperUtils.setGravity(windowGravity)
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
            }

            spIcon.apply {
                setSelection(FloatingWindowHelperUtils.IconType.getIndex(PreferenceUtil.icon))
                onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        windowIcon = FloatingWindowHelperUtils.IconType.fromIndex(position)
                        if (imageUri != null) {
                            FloatingWindowHelperUtils.setIcon(windowIcon, imageUri)
                        }
                        if (windowIcon == FloatingWindowHelperUtils.IconType.CUSTOM) {
                            imgPreview.isVisible = true
                            btnPickPhoto.isVisible = true
                        } else {
                            imgPreview.isVisible = false
                            btnPickPhoto.isVisible = false
                        }
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
            }

            edXOffset.apply {
                value = xOffset
                setOnValueChangeListener(object : ValueEditor.OnValueChangeListener {
                    override fun onValueAdd() {
                        if (xOffset in 0 .. (DensityUtil.getScreenWidth() - 52.dp)) {
                            xOffset += 1
                        }
                        value = xOffset
                        FloatingWindowHelperUtils.setXOffset(xOffset)
                    }

                    override fun onValueMinus() {
                        if (xOffset in 1 .. (DensityUtil.getScreenWidth() - 52.dp)) {
                            xOffset -= 1
                        }
                        value = xOffset
                        FloatingWindowHelperUtils.setXOffset(xOffset)
                    }

                    override fun onValueClick(result: Int?) {
                        if (result == null) return
                        if (xOffset in 0 .. (DensityUtil.getScreenWidth() - 52.dp)) {
                            xOffset = result
                            value = result
                        }
                        FloatingWindowHelperUtils.setXOffset(xOffset)
                    }

                })
            }

            edYOffset.apply {
                value = yOffset
                setOnValueChangeListener(object : ValueEditor.OnValueChangeListener {
                    override fun onValueAdd() {
                        if (yOffset in 0 .. (DensityUtil.getScreenHeight() - 36.dp)) {
                            yOffset += 1
                        }
                        value = yOffset
                        FloatingWindowHelperUtils.setYOffset(yOffset)
                    }

                    override fun onValueMinus() {
                        if (yOffset in 1 .. (DensityUtil.getScreenHeight() - 36.dp)) {
                            yOffset -= 1
                        }
                        value = yOffset
                        FloatingWindowHelperUtils.setYOffset(yOffset)
                    }

                    override fun onValueClick(result: Int?) {
                        if (result == null) return
                        if (yOffset in 0 .. (DensityUtil.getScreenHeight() - 36.dp)) {
                            yOffset = result
                            value = result
                        }
                        FloatingWindowHelperUtils.setYOffset(yOffset)
                    }

                })
            }

            /*etXOffset.apply {
                setText("$xOffset")
                addTextChangedListener {
                    if (it.isNullOrEmpty()) return@addTextChangedListener
                    xOffset = it.toString().toIntOrNull() ?: return@addTextChangedListener
                    FloatingWindowHelperUtils.setXOffset(xOffset)
                }
            }

            etYOffset.apply {
                setText("$yOffset")
                addTextChangedListener {
                    if (it.isNullOrEmpty()) return@addTextChangedListener
                    yOffset = it.toString().toIntOrNull() ?: return@addTextChangedListener
                    FloatingWindowHelperUtils.setYOffset(yOffset)
                }
            }*/

            if (imageUri != null) {
                val bitmap = BitmapFactory.decodeFile(imageUri)
                imgPreview.setImageBitmap(bitmap)
            }

            btnPickPhoto.setOnClickListener {
                requestPermission.launch(
                    arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_MEDIA_IMAGES
                    )
                )
            }

            btnOk.setOnClickListener {
                PreferenceUtil.xOffset = xOffset
                PreferenceUtil.yOffset = yOffset
                PreferenceUtil.gravity = windowGravity.type
                PreferenceUtil.icon = windowIcon.value
                PreferenceUtil.iconPath = imageUri
                finish()
            }

            btnCancel.setOnClickListener {
                FloatingWindowHelperUtils.setXOffset(PreferenceUtil.xOffset)
                FloatingWindowHelperUtils.setYOffset(PreferenceUtil.yOffset)
                FloatingWindowHelperUtils.setGravity(
                    FloatingWindowHelperUtils.GravityType.fromInt(
                        PreferenceUtil.gravity
                    )
                )
                FloatingWindowHelperUtils.setIcon(
                    FloatingWindowHelperUtils.IconType.fromInt(PreferenceUtil.icon),
                    PreferenceUtil.iconPath
                )
                finish()
            }
        }
    }

    private fun pickImage() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
        galleryLauncher.launch(intent)
    }

    private fun saveImageToCache(uri: Uri?): String? {
        if (uri == null) return null
        val inputStream = contentResolver.openInputStream(uri)
        inputStream?.use { input ->
            val extension = getFileExtension(uri.toString())
            val outputFile = File(cacheDir, "custom.$extension")
            outputFile.outputStream().use { output ->
                input.copyTo(output)
            }
            return outputFile.absolutePath
        }
        return null
    }

    private fun getFileExtension(uri: String): String {
        return MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(Uri.parse(uri)))
            ?: "jpg" // Default extension
    }

    companion object {
        private val TAG = SettingActivity::class.java.simpleName
    }
}