package cpm.com.gskmtorange.dailyentry

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import cpm.com.gskmtorange.Database.GSKOrangeDB
import cpm.com.gskmtorange.R
import cpm.com.gskmtorange.constant.CommonFunctions
import cpm.com.gskmtorange.constant.CommonString
import cpm.com.gskmtorange.xmlGetterSetter.MasterDetailerGetterSetter
import java.net.URLEncoder

class BannerActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    var bannerlistnew: ArrayList<MasterDetailerGetterSetter>? = ArrayList()

    private lateinit var preferences: SharedPreferences
    private lateinit var db: GSKOrangeDB
    private lateinit var countryId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_banner)

        val toolbar: androidx.appcompat.widget.Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.title = "Banner Dashboard"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        toolbar.setNavigationOnClickListener { 
            onBackPressedDispatcher.onBackPressed()
        }

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)

        preferences = PreferenceManager.getDefaultSharedPreferences(this)
        CommonFunctions.updateLangResources(this, preferences.getString(CommonString.KEY_LANGUAGE, ""))
        countryId = preferences.getString(CommonString.KEY_COUNTRY_ID, "") ?: ""

        db = GSKOrangeDB(this)
        db.open()
        val storetype = intent.getStringExtra("DT_LEVEL") ?: ""
        val categoryId = intent.getStringExtra("CategoryId") ?: ""

        bannerlistnew = db.getMasterDetailerData("MASTER_DETAILER",storetype,categoryId)
        /*if(!categoryId.equals("0")){
            bannerlistnew = db.getMasterDetailerData("MASTER_DETAILER",storetype,categoryId)
        }
        else{
            bannerlistnew = db.getMasterDetailerData("MASTER_DETAILER",storetype,"0")
        }*/

        Log.d("bannerlistkotlin", bannerlistnew?.size.toString())

        bannerlistnew?.let {
            if (it.isNotEmpty()) {
                recyclerView.adapter = BannerListAdapter(it) { item -> handleClick(item) }
            }
        }
    }

   /* override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.banner_menu, menu)
        return true
    }*/

   /* override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_social_media) {
            // Handle social media icon click
            return true
        }
        return super.onOptionsItemSelected(item)
    }*/

    private fun handleClick(item: MasterDetailerGetterSetter) {
        val url = if (item.dT_URL.isNotEmpty()) item.dT_URL[0] else ""
        val type = "html-webview" // Default type as not specified in MASTER_DETAILER metadata
        Log.e("clickdata", "URL = $url")

        val storeId = preferences.getString(CommonString.KEY_STORE_ID, "") ?: ""
        val merId = if (item.dtid.isNotEmpty()) item.dtid[0] else ""
        val categoryId = intent.getStringExtra("CategoryId") ?: ""
        val finalUrl = appendStoreMerQuery(url, storeId, merId)
        val storetype = intent.getStringExtra("DT_LEVEL") ?: ""
        Log.d("finalurl", finalUrl)

        val webIntent = Intent(this, WebViewActivity::class.java).apply {
            putExtra("url", finalUrl)
            putExtra("type", type)
            putExtra("storeid", storeId)
            putExtra("merid", merId)
            putExtra("categoryId", categoryId)
            putExtra("dt_level", storetype)
        }
        startActivity(webIntent)
    }

    private fun appendStoreMerQuery(url: String?, storeId: String?, merId: String?): String {
        if (url == null) return ""
        return try {
            val sb = StringBuilder(url)
            var separator = if (url.contains("?")) "&" else "?"
            if (!storeId.isNullOrEmpty()) {
                sb.append(separator).append("storeid=").append(URLEncoder.encode(storeId, "UTF-8"))
                separator = "&"
            }
            if (!merId.isNullOrEmpty()) {
                sb.append(separator).append("merid=").append(URLEncoder.encode(merId, "UTF-8"))
            }
            sb.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            url
        }
    }

    inner class BannerListAdapter(
        private val list: List<MasterDetailerGetterSetter>,
        private val listener: (MasterDetailerGetterSetter) -> Unit
    ) : RecyclerView.Adapter<BannerListAdapter.ViewHolder>() {

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val image: ImageView = itemView.findViewById(R.id.imgThumbnail)
            val name: TextView = itemView.findViewById(R.id.tvName)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_banner_list, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = list[position]
            // Accessing first element of internal list as per parinaam pattern
            val url = if (item.dT_THUMBNAIL.isNotEmpty()) item.dT_THUMBNAIL[0] else ""
            val displayName = if (item.dT_NAME.isNotEmpty()) item.dT_NAME[0] else ""
            
            holder.name.text = displayName
            
            Glide.with(holder.itemView.context)
                .load(url)
                .placeholder(R.mipmap.ic_launcher)
                .transform(RoundedCorners(15))
                .into(holder.image)

            holder.itemView.setOnClickListener { listener(item) }
        }
        override fun getItemCount(): Int = list.size
    }
}
