package com.sambath.kunkhmer.screen.fighter

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.app.App
import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_desc
import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_height
import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_name
import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_nationality
import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_weight
import kotlinx.android.synthetic.main.fragment_create_fighter.view.submitButton
import kotlinx.android.synthetic.main.fragment_create_fighter.view.uploadButton
import kotlinx.android.synthetic.main.fragment_create_fighter.view.uploadedImageView


class CreateFighterFragment : Fragment() {
    private var _root: View? = null
    private val binding get() = _root!!
    private var imageUri: Uri? = null
    private lateinit var fighterViewModel: FighterViewModel
    private lateinit var loadingProgressBar: ProgressBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        _root = inflater.inflate(R.layout.fragment_create_fighter, container, false)

        loadingProgressBar = binding.findViewById(R.id.loadingProgressBar)
        fighterViewModel = FighterViewModel(App.injectApiService(), App.injectPrefHelper())
        fighterViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })

        binding.uploadButton.setOnClickListener {
            openImagePicker()
        }

        binding.submitButton.setOnClickListener {
            // Show loading view
            loadingProgressBar.visibility = View.VISIBLE

            val imagePath = imageUri?.let { it1 -> getImagePathFromUri(it1) }
            if (imagePath != null) {
                fighterViewModel.createFighter(
                    binding.et_name.text.toString(),
                    binding.et_desc.text.toString(),
                    binding.et_weight.text.toString(),
                    binding.et_height.text.toString(),
                    binding.et_nationality.text.toString(),
                    imagePath
                )
            } else {
                fighterViewModel.createFighter(
                    binding.et_name.text.toString(),
                    binding.et_desc.text.toString(),
                    binding.et_weight.text.toString(),
                    binding.et_height.text.toString(),
                    binding.et_nationality.text.toString(),
                    ""
                )
            }
        }

        setDefault()
        return binding
    }

    private fun render(state: FighterViewState) {
        if (state.isLoginSuccess) {
            Toast.makeText(context, "Create Success...", Toast.LENGTH_LONG).show()
            // Hide loading view
            loadingProgressBar.visibility = View.GONE

            binding.et_name.setText("")
            binding.et_desc.setText("")
            binding.et_weight.setText("")
            binding.et_height.setText("")
            binding.et_nationality.setText("")
            binding.uploadedImageView.setImageDrawable(null)
        }
    }

    private val imagePicker: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val data: Intent? = result.data
                if (data != null) {
                    imageUri = data.data // The URI of the selected image
                    if (imageUri != null) {
                        // Load and display the selected image in the ImageView
                        binding.uploadedImageView.setImageURI(imageUri)
                    }
                }
            }
        }

    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        imagePicker.launch(intent)
    }

    private fun getImagePathFromUri(uri: Uri): String? {
        val contentResolver = requireContext().contentResolver
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            it.moveToFirst()
            val index = it.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            return it.getString(index)
        }
        return null
    }

    private fun setDefault() {
        binding.et_name.setText("John Cena")
        binding.et_desc.setText("John Cena")
        binding.et_weight.setText("66")
        binding.et_height.setText("1,75")
        binding.et_nationality.setText("US")
    }
}