package cz.muni.sutralog.ui.detail

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.text.HtmlCompat
import androidx.core.text.HtmlCompat.fromHtml
import androidx.documentfile.provider.DocumentFile
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import cz.muni.sutralog.R
import cz.muni.sutralog.data.RockPresentableListItem
import cz.muni.sutralog.databinding.RockDetailBinding
import cz.muni.sutralog.lib.SutralogStaticLib.Companion.dateToString
import cz.muni.sutralog.lib.SutralogStaticLib.Companion.getGoogleMapsLink
import cz.muni.sutralog.repository.CategoryRepository
import cz.muni.sutralog.repository.PhotoRepository
import cz.muni.sutralog.repository.RockRepository
import cz.muni.sutralog.ui.list.PhotoAdapter


class RockDetailFragment : Fragment() {

    private lateinit var binding: RockDetailBinding

    private lateinit var adapter: PhotoAdapter

    private val rockRepository: RockRepository by lazy {
        RockRepository(requireContext())
    }

    private val categoryRepository: CategoryRepository by lazy {
        CategoryRepository(requireContext())
    }

    private val photoRepository: PhotoRepository by lazy {
        PhotoRepository(requireContext())
    }

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

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val rockId = RockDetailFragmentArgs.fromBundle(requireArguments()).rockId
        val rock = rockRepository.getRockById(rockId)
        setRockLayoutValues(rock)

        var photos = photoRepository.getPhotosByRockId(rock.id)
        if (photos == null || photos.isEmpty()) {
            binding.rockImageRecyclerView.visibility = View.GONE
        }

        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.edit -> findNavController().navigate(
                    RockDetailFragmentDirections
                        .actionRockDetailToRockEdit(rock)
                )
                R.id.remove -> {
                    AlertDialog.Builder(requireContext())
                        .setMessage("Opravdu smazat?")
                        .setCancelable(false)
                        .setNegativeButton("Zrušit") { dialogInterface: DialogInterface, i: Int ->
                            dialogInterface.dismiss()
                        }
                        .setPositiveButton("Smazat") { dialogInterface: DialogInterface, i: Int ->
                            rockRepository.deleteRock(rock)
                            findNavController().navigateUp()
                        }
                        .show()
                }
            }
            true
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == AppCompatActivity.RESULT_OK) {
            val treeUri = data?.data
            if (treeUri != null) {
                requireContext().contentResolver.takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val fileDoc = DocumentFile.fromTreeUri(requireContext(), treeUri)
            }

        }
    }

    private fun setRockLayoutValues(rock: RockPresentableListItem) {
        adapter = PhotoAdapter(
            onItemClick = {

            },
            onItemLongClick = {
                true
            }
        )

        binding.rockImageRecyclerView.adapter = adapter

        val category = categoryRepository.getCategoryById(rock.categoryId)

        binding.rockCategory.text = category.name
        binding.toolbar.title = "${rock.name} (${rock.id})"
        binding.rockCount.text = rock.count?.let{ count -> "$count ks"}
        binding.rockDate.text = rock.date?.let { date -> dateToString(date) }
        binding.rockLocality.text = rock.locality
        if (rock.latitude != null && rock.longitude != null) {
            binding.rockMapLink.text =
                fromHtml(getGoogleMapsLink(rock.latitude!!, rock.longitude!!), HtmlCompat.FROM_HTML_MODE_COMPACT)
            binding.rockMapLink.movementMethod = LinkMovementMethod.getInstance()
        }
        binding.rockWhere.text = rock.where
        binding.rockFrom.text = rock.from
        binding.rockDescription.text = rock.description
        binding.rockComment.text = rock.comment

        val photos = photoRepository.getPhotosByRockId(rock.id)
        if (photos.isNotEmpty()) {
            adapter.submitList(photos)
        }
    }
}