package io.agora.scene.convoai.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import io.agora.scene.common.ui.BaseFragment
import io.agora.scene.common.util.GlideImageLoader
import io.agora.scene.convoai.CovLogger
import io.agora.scene.convoai.api.CovAgentPreset
import io.agora.scene.convoai.constant.CovAgentManager
import io.agora.scene.convoai.databinding.CovFragmentOfficialAgentBinding
import io.agora.scene.convoai.databinding.CovItemOfficialAgentBinding
import io.agora.scene.convoai.ui.CovLivingActivity
import io.agora.scene.convoai.ui.vm.CovListViewModel

class CovOfficialAgentFragment : BaseFragment<CovFragmentOfficialAgentBinding>() {

    companion object{
        private const val TAG = "CovOfficialAgentFragment"
    }

    private lateinit var adapter: OfficialAgentAdapter
    private val viewModel: CovListViewModel by activityViewModels()

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): CovFragmentOfficialAgentBinding? {
        return CovFragmentOfficialAgentBinding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        setupAdapter()
        observeViewModel()
    }


    private fun initViews() {
        mBinding?.apply {
            // Setup retry button click listener
            btnRetry.setOnClickListener {
                viewModel.loadOfficialAgents()
            }
            
            // Setup SwipeRefreshLayout
            swipeRefreshLayout.setOnRefreshListener {
                CovLogger.d(TAG, "SwipeRefreshLayout triggered")
                viewModel.loadOfficialAgents()
            }
            
            // Set refresh colors
            swipeRefreshLayout.setColorSchemeResources(
                io.agora.scene.common.R.color.ai_brand_main6
            )
        }
    }

    private fun setupAdapter() {
        adapter = OfficialAgentAdapter { preset ->
            onPresetSelected(preset)
        }
        mBinding?.apply {
            rvOfficialAgents.adapter = adapter
        }
    }

    private fun observeViewModel() {
        CovLogger.d(TAG, "Setting up ViewModel observer")
        
        // Observe data changes
        viewModel.officialAgents.observe(viewLifecycleOwner) { presets ->
            CovLogger.d(TAG, "Data updated: ${presets.size} items")
            adapter.updateData(presets)
        }
        
        // Observe state changes
        viewModel.officialState.observe(viewLifecycleOwner) { state ->
            CovLogger.d(TAG, "State changed: $state")
            when (state) {
                is CovListViewModel.AgentListState.Loading -> {
                    // Loading state is handled by SwipeRefreshLayout, no need for additional loading UI
                }
                is CovListViewModel.AgentListState.Success -> {
                    showContent()
                }
                is CovListViewModel.AgentListState.Error -> {
                    showError()
                }
                is CovListViewModel.AgentListState.Empty -> {
                    showError()
                }
            }
        }
    }

    private fun showContent() {
        mBinding?.apply {
            rvOfficialAgents.visibility = View.VISIBLE
            llError.visibility = View.GONE
            swipeRefreshLayout.isEnabled = true
            swipeRefreshLayout.isRefreshing = false
        }
    }

    private fun showError() {
        mBinding?.apply {
            rvOfficialAgents.visibility = View.GONE
            llError.visibility = View.VISIBLE
            swipeRefreshLayout.isEnabled = false
            swipeRefreshLayout.isRefreshing = false
        }
    }

    private fun onPresetSelected(preset: CovAgentPreset) {
        CovAgentManager.setPreset(preset)
        CovLogger.d(TAG, "Selected preset: ${preset.name}")
        context?.let {
            it.startActivity(Intent(it, CovLivingActivity::class.java))
        }
    }

    inner class OfficialAgentAdapter(
        private val onItemClick: (CovAgentPreset) -> Unit
    ) : RecyclerView.Adapter<OfficialAgentAdapter.OfficialAgentViewHolder>() {

        private var presets: List<CovAgentPreset> = emptyList()

        fun updateData(newPresets: List<CovAgentPreset>) {
            presets = newPresets
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OfficialAgentViewHolder {
            return OfficialAgentViewHolder(
                CovItemOfficialAgentBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: OfficialAgentViewHolder, position: Int) {
            holder.bind(presets[position])
        }

        override fun getItemCount(): Int = presets.size

        inner class OfficialAgentViewHolder(private val binding: CovItemOfficialAgentBinding) : RecyclerView.ViewHolder
            (binding.root) {

            fun bind(preset: CovAgentPreset) {
                binding.apply {
                    tvTitle.text = preset.display_name
                    tvDescription.isVisible  =  preset.description.isNotEmpty()
                    tvDescription.text = preset.description
                    if (preset.avatar_url.isNullOrEmpty()) {
                        ivAvatar.setImageResource(io.agora.scene.common.R.drawable.common_default_agent)
                    } else {
                        GlideImageLoader.load(
                            ivAvatar,
                            preset.avatar_url,
                            io.agora.scene.common.R.drawable.common_default_agent,
                            io.agora.scene.common.R.drawable.common_default_agent
                        )
                    }
                    rootView.setOnClickListener {
                        val position = adapterPosition
                        if (position != RecyclerView.NO_POSITION) {
                            onItemClick.invoke(presets[position])
                        }
                    }
                }
            }
        }
    }
} 