package com.demoscene.tv

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.leanback.app.DetailsSupportFragment
import androidx.leanback.app.DetailsSupportFragmentBackgroundController
import androidx.leanback.widget.*
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.demoscene.tv.data.DemoDataProvider
import com.demoscene.tv.model.Demo

class DetailsFragment : DetailsSupportFragment() {
    
    private lateinit var demo: Demo
    private lateinit var backgroundController: DetailsSupportFragmentBackgroundController
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        val demoId = arguments?.getString(DetailsActivity.EXTRA_DEMO_ID) ?: return
        demo = DemoDataProvider.getDemoById(demoId) ?: return
        
        setupAdapter()
        setupBackground()
        onItemViewClickedListener = ItemViewClickedListener()
    }
    
    private fun setupAdapter() {
        val detailsOverview = DetailsOverviewRow(demo)
        
        // Load demo image
        Glide.with(requireContext())
            .asBitmap()
            .load(demo.getCardImageUrl())
            .into(object : SimpleTarget<Bitmap>() {
                override fun onResourceReady(
                    bitmap: Bitmap,
                    transition: Transition<in Bitmap>?
                ) {
                    detailsOverview.setImageBitmap(requireContext(), bitmap)
                }
            })
        
        // Add actions
        val actionAdapter = ArrayObjectAdapter()
        actionAdapter.add(
            Action(
                ACTION_PLAY,
                "Play",
                "Watch this demo on YouTube"
            )
        )
        actionAdapter.add(
            Action(
                ACTION_INFO,
                "Info",
                "View on pouet.net"
            )
        )
        detailsOverview.actionsAdapter = actionAdapter
        
        // Setup presenter
        val presenterSelector = ClassPresenterSelector()
        val detailsPresenter = DetailsOverviewRowPresenter(DetailsDescriptionPresenter())
        detailsPresenter.backgroundColor = ContextCompat.getColor(requireContext(), R.color.detail_background)
        detailsPresenter.isStyleLarge = true
        detailsPresenter.sharedElementEnterTransition = requireActivity()
            .window.sharedElementEnterTransition
        presenterSelector.addClassPresenter(DetailsOverviewRow::class.java, detailsPresenter)
        
        val rowsAdapter = ArrayObjectAdapter(presenterSelector)
        rowsAdapter.add(detailsOverview)
        
        // Add related demos (simple version - just show more from same group)
        addRelatedDemos(rowsAdapter)
        
        adapter = rowsAdapter
    }
    
    private fun addRelatedDemos(rowsAdapter: ArrayObjectAdapter) {
        val relatedDemos = DemoDataProvider.getCategories()
            .flatMap { it.demos }
            .filter { it.group == demo.group && it.id != demo.id }
            .take(5)
        
        if (relatedDemos.isNotEmpty()) {
            val listRowAdapter = ArrayObjectAdapter(CardPresenter())
            relatedDemos.forEach { listRowAdapter.add(it) }
            
            val header = HeaderItem("More from ${demo.group}")
            rowsAdapter.add(ListRow(header, listRowAdapter))
        }
    }
    
    private fun setupBackground() {
        backgroundController = DetailsSupportFragmentBackgroundController(this)
        
        Glide.with(requireContext())
            .load(demo.getCardImageUrl())
            .centerCrop()
            .error(R.drawable.default_background)
            .into(object : SimpleTarget<Drawable>() {
                override fun onResourceReady(
                    drawable: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    backgroundController.coverBitmap = null
                    backgroundController.enableParallax()
                }
            })
    }
    
    private inner class ItemViewClickedListener : OnItemViewClickedListener {
        override fun onItemClicked(
            itemViewHolder: Presenter.ViewHolder?,
            item: Any?,
            rowViewHolder: RowPresenter.ViewHolder?,
            row: Row?
        ) {
            when (item) {
                is Action -> {
                    when (item.id) {
                        ACTION_PLAY -> {
                            // Launch playback activity
                            val intent = Intent(requireContext(), PlaybackActivity::class.java)
                            intent.putExtra(PlaybackActivity.EXTRA_DEMO_ID, demo.id)
                            startActivity(intent)
                        }
                        ACTION_INFO -> {
                            // Could open pouet.net link in browser
                            // For now, just toast
                            android.widget.Toast.makeText(
                                requireContext(),
                                "Would open pouet.net/${demo.id}",
                                android.widget.Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
                is Demo -> {
                    // Clicked on related demo
                    val intent = Intent(requireContext(), DetailsActivity::class.java)
                    intent.putExtra(DetailsActivity.EXTRA_DEMO_ID, (item as Demo).id)
                    startActivity(intent)
                }
            }
        }
    }
    
    inner class DetailsDescriptionPresenter : AbstractDetailsDescriptionPresenter() {
        override fun onBindDescription(vh: ViewHolder, item: Any) {
            val demo = item as Demo
            
            vh.title.text = demo.name
            vh.subtitle.text = "${demo.group} • ${demo.platform}"
            vh.body.text = buildString {
                append(demo.description)
                append("\n\n")
                append("Released: ${demo.releaseDate}")
                if (demo.party.isNotEmpty()) {
                    append("\nParty: ${demo.party}")
                }
                append("\nType: ${demo.type}")
                append("\nRating: ${"★".repeat(demo.rating.toInt())}${"☆".repeat(5 - demo.rating.toInt())}")
            }
        }
    }
    
    companion object {
        private const val ACTION_PLAY = 1L
        private const val ACTION_INFO = 2L
    }
}
