package com.demoscene.tv

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.leanback.app.BackgroundManager
import androidx.leanback.app.BrowseSupportFragment
import androidx.leanback.widget.*
import androidx.core.app.ActivityOptionsCompat
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 MainFragment : BrowseSupportFragment() {
    
    private lateinit var backgroundManager: BackgroundManager
    private var backgroundTimer: java.util.Timer? = null
    private var backgroundUri: String? = null
    private val handler = Handler(Looper.getMainLooper())
    
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        
        setupUI()
        loadRows()
        setupEventListeners()
    }
    
    private fun setupUI() {
        // Set title and badge
        title = "DemoScene TV"
        headersState = HEADERS_ENABLED
        isHeadersTransitionOnBackEnabled = true
        
        // Set brand color
        brandColor = ContextCompat.getColor(requireContext(), R.color.primary)
        searchAffordanceColor = ContextCompat.getColor(requireContext(), R.color.accent)
        
        // Setup background
        backgroundManager = BackgroundManager.getInstance(requireActivity())
        backgroundManager.attach(requireActivity().window)
        updateBackground(R.drawable.default_background)
    }
    
    private fun loadRows() {
        val rowsAdapter = ArrayObjectAdapter(ListRowPresenter())
        val cardPresenter = CardPresenter()
        
        // Get demo categories from data provider
        val categories = DemoDataProvider.getCategories()
        
        categories.forEach { category ->
            val listRowAdapter = ArrayObjectAdapter(cardPresenter)
            category.demos.forEach { demo ->
                listRowAdapter.add(demo)
            }
            
            val header = HeaderItem(category.title)
            rowsAdapter.add(ListRow(header, listRowAdapter))
        }
        
        adapter = rowsAdapter
    }
    
    private fun setupEventListeners() {
        onItemViewClickedListener = ItemViewClickedListener()
        onItemViewSelectedListener = ItemViewSelectedListener()
    }
    
    private inner class ItemViewClickedListener : OnItemViewClickedListener {
        override fun onItemClicked(
            itemViewHolder: Presenter.ViewHolder?,
            item: Any?,
            rowViewHolder: RowPresenter.ViewHolder?,
            row: Row?
        ) {
            if (item is Demo) {
                val intent = Intent(requireContext(), DetailsActivity::class.java)
                intent.putExtra(DetailsActivity.EXTRA_DEMO_ID, item.id)
                
                val bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                    requireActivity(),
                    (itemViewHolder?.view as ImageCardView).mainImageView,
                    DetailsActivity.SHARED_ELEMENT_NAME
                ).toBundle()
                
                startActivity(intent, bundle)
            }
        }
    }
    
    private inner class ItemViewSelectedListener : OnItemViewSelectedListener {
        override fun onItemSelected(
            itemViewHolder: Presenter.ViewHolder?,
            item: Any?,
            rowViewHolder: RowPresenter.ViewHolder?,
            row: Row?
        ) {
            if (item is Demo) {
                backgroundTimer?.cancel()
                backgroundTimer = java.util.Timer()
                backgroundTimer?.schedule(
                    object : java.util.TimerTask() {
                        override fun run() {
                            handler.post {
                                updateBackground(item.getCardImageUrl())
                            }
                        }
                    },
                    300
                )
            }
        }
    }
    
    private fun updateBackground(uri: String?) {
        val width = backgroundManager.maxWidth
        val height = backgroundManager.maxHeight
        
        Glide.with(requireContext())
            .load(uri)
            .centerCrop()
            .error(R.drawable.default_background)
            .into(object : SimpleTarget<Drawable>(width, height) {
                override fun onResourceReady(
                    drawable: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    backgroundManager.drawable = drawable
                }
            })
    }
    
    private fun updateBackground(resourceId: Int) {
        val drawable = ContextCompat.getDrawable(requireContext(), resourceId)
        backgroundManager.drawable = drawable
    }
    
    override fun onDestroy() {
        super.onDestroy()
        backgroundTimer?.cancel()
    }
}
