package com.gallery.free.wallpaper.fragment

import android.Manifest
import android.R
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
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.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.gallery.free.wallpaper.LocalPreActivity
import com.gallery.free.wallpaper.MainActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job

class SeFragment : Fragment() {

    private var currentRating = 0
    private var loadingJob: Job? = null
    private val coroutineScope = CoroutineScope(Dispatchers.Main)

    companion object {
        private const val REQUEST_GALLERY_PERMISSION = 1001
        private const val REQUEST_PREVIEW = 1002
        private const val TAG = "SettingFragment"
        const val EXTRA_FROM_PREVIEW = "from_preview"
        fun newInstance(): SeFragment {
            return SeFragment()
        }
    }
    private val galleryLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        Log.d(TAG, "galleryLauncher返回: resultCode=${result.resultCode}")

        if (result.resultCode == Activity.RESULT_OK && result.data != null) {
            val uri = result.data?.data
            if (uri != null) {
                Log.d(TAG, "从图库选择了图片: $uri")

                val intent = Intent(requireContext(), LocalPreActivity::class.java).apply {
                    putExtra(LocalPreActivity.Companion.EXTRA_IMAGE_URI, uri.toString())
                    putExtra(LocalPreActivity.Companion.EXTRA_FROM_SETTING, true)
                    addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                }

                startActivity(intent)
                activity?.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                activity?.finish()
            } else {
                showToast("Failed to get image")
            }
        } else {
            Log.d(TAG, "用户取消了图库选择")
            val intent = Intent(requireContext(), MainActivity::class.java).apply {
                putExtra("SHOW_SETTING_FRAGMENT", true)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            }
            requireContext().startActivity(intent)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d(TAG, "onActivityResult: requestCode=$requestCode, resultCode=$resultCode")

        when (requestCode) {
            LocalPreActivity.Companion.RESULT_SET_SUCCESS -> {
                // 处理预览页面返回结果
                when (resultCode) {
                    LocalPreActivity.Companion.RESULT_SET_SUCCESS -> {
                        Log.d(TAG, "壁纸设置成功，已返回设置页面")
                        showToast("壁纸设置成功！")
                    }
                    Activity.RESULT_CANCELED -> {
                        Log.d(TAG, "用户取消了壁纸设置")
                    }
                    else -> {
                        Log.d(TAG, "预览页面返回未知结果: $resultCode")
                    }
                }
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(com.gallery.free.wallpaper.R.layout.fragment_se, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setVersionNumber(view)
        setupRateUsClickListeners(view)
        setupChoosePhotosClickListeners(view)

        checkIfReturnedFromPreview()
    }

    private fun checkIfReturnedFromPreview() {
        val activity = activity as? MainActivity
        activity?.intent?.let { intent ->
            if (intent.hasExtra("SHOW_SETTING_FRAGMENT")) {
                Log.d(TAG, "从预览页面返回，显示SettingFragment")
                intent.removeExtra("SHOW_SETTING_FRAGMENT")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "SettingFragment恢复显示")
        checkIfReturnedFromPreview()
    }


    override fun onDestroyView() {
        super.onDestroyView()
        loadingJob?.cancel()
    }

    @SuppressLint("SetTextI18n")
    private fun setVersionNumber(view: View) {
        try {
            val packageInfo = requireContext().packageManager
                .getPackageInfo(requireContext().packageName, 0)

            val versionName = packageInfo.versionName

            val versionValue = view.findViewById<TextView>(com.gallery.free.wallpaper.R.id.versionValue)
            if (versionValue != null) {
                versionValue.text = "$versionName"
            }

        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            val versionValue = view.findViewById<TextView>(com.gallery.free.wallpaper.R.id.versionValue)
            if (versionValue != null) {
                versionValue.text = "1.0"
            }
        }
    }

    private fun setupChoosePhotosClickListeners(view: View) {
        val choosePhotosLayout = view.findViewById<View>(com.gallery.free.wallpaper.R.id.choosePhotosLayout)
        val choosePhotosText = view.findViewById<View>(com.gallery.free.wallpaper.R.id.choosePhotosText)
        val choosePhotosIcon = view.findViewById<View>(com.gallery.free.wallpaper.R.id.choosePhotosIcon)
        val choosePhotosArrow = view.findViewById<View>(com.gallery.free.wallpaper.R.id.choosePhotosArrow)

        val clickListener = View.OnClickListener {
            openGalleryForImage()
        }

        choosePhotosLayout?.setOnClickListener(clickListener)
        choosePhotosText?.setOnClickListener(clickListener)
        choosePhotosIcon?.setOnClickListener(clickListener)
        choosePhotosArrow?.setOnClickListener(clickListener)
    }

    private fun setupRateUsClickListeners(view: View) {
        val rateUsLayout = view.findViewById<View>(com.gallery.free.wallpaper.R.id.rateUsLayout)
        val rateUsText = view.findViewById<View>(com.gallery.free.wallpaper.R.id.rateUsText)
        val rateUsIcon = view.findViewById<View>(com.gallery.free.wallpaper.R.id.rateUsIcon)
        val rateUsArrow = view.findViewById<View>(com.gallery.free.wallpaper.R.id.rateUsArrow)

        val clickListener = View.OnClickListener { showRateUsDialog() }

        rateUsLayout?.setOnClickListener(clickListener)
        rateUsText?.setOnClickListener(clickListener)
        rateUsIcon?.setOnClickListener(clickListener)
        rateUsArrow?.setOnClickListener(clickListener)

        if (rateUsLayout == null && rateUsText == null && rateUsIcon == null && rateUsArrow == null) {
            println("Warning: No rate us views found in fragment_setting_two.xml")
        }
    }

    private fun openGalleryForImage() {
        // 检查权限
        if (hasGalleryPermission()) {
            launchGallery()
        } else {
            requestGalleryPermission()
        }
    }

    private fun getGalleryPermission(): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        } else {
            Manifest.permission.READ_EXTERNAL_STORAGE
        }
    }

    private fun hasGalleryPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            requireContext(),
            getGalleryPermission()
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestGalleryPermission() {
        val permission = getGalleryPermission()
        if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), permission)) {
            // 解释为什么需要权限
            showPermissionRationaleDialog(permission)
        } else {
            // 直接请求权限
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(permission),
                REQUEST_GALLERY_PERMISSION
            )
        }
    }

    private fun showPermissionRationaleDialog(permission: String) {
        AlertDialog.Builder(requireContext())
            .setTitle("Permission Required")
            .setMessage("Need permission to access your photos to set as wallpaper")
            .setPositiveButton("OK") { _, _ ->
                ActivityCompat.requestPermissions(
                    requireActivity(),
                    arrayOf(permission),
                    REQUEST_GALLERY_PERMISSION
                )
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun launchGallery() {
        try {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            // 使用registerForActivityResult的方式
            galleryLauncher.launch(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            showToast("Cannot open gallery")
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            REQUEST_GALLERY_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchGallery()
                } else {
                    showToast("Permission denied")
                }
            }
        }
    }

    private fun showRateUsDialog() {
        try {
            val dialogView = LayoutInflater.from(requireContext()).inflate(com.gallery.free.wallpaper.R.layout.dialog_rateus, null)

            val dialog = AlertDialog.Builder(requireContext())
                .setView(dialogView)
                .setCancelable(true)
                .create()

            dialog.window?.setBackgroundDrawableResource(R.color.transparent)

            currentRating = 0
            val btnRate = dialogView.findViewById<Button>(com.gallery.free.wallpaper.R.id.btn_rate)
            btnRate?.isEnabled = false

            setupStarClickListeners(dialogView, btnRate)

            val btnCancel = dialogView.findViewById<View>(com.gallery.free.wallpaper.R.id.btn_cancel)
            btnCancel?.setOnClickListener {
                dialog.dismiss()
            }

            btnRate?.setOnClickListener {
                if (currentRating > 0) {
                    dialog.dismiss()
                }
            }

            dialog.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setupStarClickListeners(dialogView: View, rateButton: Button?) {
        val stars = listOf(
            dialogView.findViewById<ImageView>(com.gallery.free.wallpaper.R.id.star1),
            dialogView.findViewById<ImageView>(com.gallery.free.wallpaper.R.id.star2),
            dialogView.findViewById<ImageView>(com.gallery.free.wallpaper.R.id.star3),
            dialogView.findViewById<ImageView>(com.gallery.free.wallpaper.R.id.star4),
            dialogView.findViewById<ImageView>(com.gallery.free.wallpaper.R.id.star5)
        )

        if (stars.any { it == null }) {
            println("Warning: Some star views are missing in dialog_rate_us_two.xml")
            return
        }

        stars.forEachIndexed { index, star ->
            star?.setOnClickListener {
                val clickedRating = index + 1
                updateStarRating(stars, clickedRating, rateButton)
            }
        }
    }

    private fun updateStarRating(stars: List<ImageView?>, rating: Int, rateButton: Button?) {
        currentRating = rating

        stars.forEachIndexed { index, star ->
            if (index < rating) {
                star?.setImageResource(com.gallery.free.wallpaper.R.drawable.star_picked)
            } else {
                star?.setImageResource(com.gallery.free.wallpaper.R.drawable.star_disabled)
            }
        }

        if (rating > 0) {
            rateButton?.isEnabled = true
            rateButton?.setBackgroundResource(com.gallery.free.wallpaper.R.drawable.button_rateit)
        } else {
            rateButton?.isEnabled = false
            rateButton?.setBackgroundResource(com.gallery.free.wallpaper.R.drawable.button_rateit_disa)
        }
    }
}