package com.example.offlinestore1

import android.graphics.Color
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView

class AppAdapter(
    private val appList: List<AppModel>,
    var isGridMode: Boolean,
    private val onPrimaryClick: (AppModel) -> Unit,
    private val onUninstallClick: (AppModel) -> Unit
) : RecyclerView.Adapter<AppAdapter.AppViewHolder>() {

    class AppViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val rootCard: MaterialCardView = view.findViewById(R.id.rootCard)
        val rootItem: LinearLayout = view.findViewById(R.id.rootItem)
        val imgIcon: ImageView = view.findViewById(R.id.imgIcon)
        val txtName: TextView = view.findViewById(R.id.txtName)
        val txtPkg: TextView = view.findViewById(R.id.txtPkg)
        val txtSize: TextView = view.findViewById(R.id.txtSize)
        val txtInstalledStatus: TextView = view.findViewById(R.id.txtInstalledStatus)
        val btnPrimary: Button = view.findViewById(R.id.btnPrimary)
        val btnUninstall: Button = view.findViewById(R.id.btnUninstall)
        val progressInstall: ProgressBar = view.findViewById(R.id.progressInstall)
        val txtProgress: TextView = view.findViewById(R.id.txtProgress)
        val layoutProgress: LinearLayout = view.findViewById(R.id.layoutProgress)
        val layoutButtons: LinearLayout = view.findViewById(R.id.layoutButtons)
        val layoutInfo: LinearLayout = view.findViewById(R.id.layoutInfo)
    }

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

    override fun onBindViewHolder(holder: AppViewHolder, position: Int) {
        val app = appList[position]
        val context = holder.itemView.context

        holder.txtName.text = app.name
        holder.txtPkg.text = app.packageName
        holder.txtPkg.setTextColor(if (app.isInstalled) Color.parseColor("#4CAF50") else Color.parseColor("#757575"))
        
        holder.txtSize.text = app.sizeText
        holder.imgIcon.setImageDrawable(app.icon)

        holder.txtInstalledStatus.visibility = if (app.isInstalled && !isGridMode) View.VISIBLE else View.GONE
        holder.txtInstalledStatus.text = context.getString(R.string.status_installed)

        holder.btnUninstall.setTextColor(Color.parseColor("#E53935"))
        holder.btnUninstall.setBackgroundResource(R.drawable.bg_button_light)
        holder.btnUninstall.text = context.getString(R.string.btn_uninstall)
        
        holder.txtName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
        holder.txtPkg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
        holder.txtSize.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
        
        holder.btnPrimary.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10.5f)
        holder.btnPrimary.setPadding(0, 0, 0, 0)
        holder.btnPrimary.includeFontPadding = false
        
        holder.btnUninstall.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10.5f)
        holder.btnUninstall.setPadding(0, 0, 0, 0)
        holder.btnUninstall.includeFontPadding = false

        val uninstallParams = holder.btnUninstall.layoutParams as LinearLayout.LayoutParams
        val primaryParams = holder.btnPrimary.layoutParams as LinearLayout.LayoutParams
        val infoParams = holder.layoutInfo.layoutParams as LinearLayout.LayoutParams
        val iconParams = holder.imgIcon.layoutParams as LinearLayout.LayoutParams
        val buttonsParams = holder.layoutButtons.layoutParams as LinearLayout.LayoutParams

        val margin6 = 6.toPx(context)
        val btnHeight = 34.toPx(context)

        primaryParams.height = btnHeight
        uninstallParams.height = btnHeight

        if (isGridMode) {
            holder.rootItem.orientation = LinearLayout.VERTICAL
            holder.layoutInfo.gravity = Gravity.CENTER
            holder.txtName.gravity = Gravity.CENTER
            holder.txtPkg.gravity = Gravity.CENTER
            holder.txtSize.gravity = Gravity.CENTER
            iconParams.gravity = Gravity.CENTER_HORIZONTAL
            
            infoParams.width = LinearLayout.LayoutParams.MATCH_PARENT
            infoParams.weight = 0f
            
            buttonsParams.width = LinearLayout.LayoutParams.MATCH_PARENT
            holder.layoutButtons.orientation = LinearLayout.HORIZONTAL
            holder.layoutButtons.layoutDirection = View.LAYOUT_DIRECTION_RTL
        } else {
            holder.rootItem.orientation = LinearLayout.HORIZONTAL
            holder.layoutInfo.gravity = Gravity.START or Gravity.CENTER_VERTICAL
            holder.txtName.gravity = Gravity.START
            holder.txtPkg.gravity = Gravity.START
            holder.txtSize.gravity = Gravity.START
            holder.txtInstalledStatus.gravity = Gravity.START

            iconParams.gravity = Gravity.CENTER_VERTICAL

            infoParams.width = 0
            infoParams.weight = 1f
            infoParams.setMargins(8.toPx(context), 0, 8.toPx(context), 0)
            
            buttonsParams.width = 125.toPx(context) 
            holder.layoutButtons.orientation = LinearLayout.VERTICAL
        }

        if (app.installState == "copying" || app.installState == "installing") {
            holder.layoutProgress.visibility = View.VISIBLE
            holder.layoutButtons.visibility = View.GONE
            holder.progressInstall.isIndeterminate = true
            holder.txtProgress.text = app.statusText
        } else {
            holder.layoutProgress.visibility = View.GONE
            holder.layoutButtons.visibility = View.VISIBLE

            if (app.isInstalled) {
                holder.btnUninstall.visibility = View.VISIBLE
                
                // שימוש בנתון המוכן מראש לשיפור הגלילה
                if (app.versionCode > app.installedVersionCode && app.installedVersionCode != -1) {
                    holder.btnPrimary.text = context.getString(R.string.btn_update)
                    holder.btnPrimary.setTextColor(Color.parseColor("#6C8F5E"))
                    holder.btnPrimary.setBackgroundResource(R.drawable.bg_button_green_outline)
                } else {
                    holder.btnPrimary.text = context.getString(R.string.btn_open)
                    holder.btnPrimary.setTextColor(Color.parseColor("#6D8FCF"))
                    holder.btnPrimary.setBackgroundResource(R.drawable.bg_button_blue_outline)
                }
            } else {
                holder.btnUninstall.visibility = View.GONE
                holder.btnPrimary.text = context.getString(R.string.btn_install)
                holder.btnPrimary.setTextColor(Color.parseColor("#6C8F5E"))
                holder.btnPrimary.setBackgroundResource(R.drawable.bg_button_green_outline)
            }

            if (holder.btnUninstall.visibility == View.VISIBLE) {
                if (isGridMode) {
                    uninstallParams.width = 0
                    uninstallParams.weight = 1f
                    uninstallParams.marginEnd = margin6
                    primaryParams.width = 0
                    primaryParams.weight = 1f
                } else {
                    uninstallParams.width = LinearLayout.LayoutParams.MATCH_PARENT
                    uninstallParams.weight = 0f
                    primaryParams.width = LinearLayout.LayoutParams.MATCH_PARENT
                    primaryParams.weight = 0f
                    primaryParams.topMargin = margin6
                }
            } else {
                primaryParams.width = LinearLayout.LayoutParams.MATCH_PARENT
                primaryParams.weight = 0f
                primaryParams.topMargin = 0
            }
        }

        holder.imgIcon.layoutParams = iconParams
        holder.layoutInfo.layoutParams = infoParams
        holder.layoutButtons.layoutParams = buttonsParams
        holder.btnUninstall.layoutParams = uninstallParams
        holder.btnPrimary.layoutParams = primaryParams

        holder.btnPrimary.setOnClickListener { 
            it.startClickAnimation()
            onPrimaryClick(app) 
        }
        holder.btnUninstall.setOnClickListener { 
            it.startClickAnimation()
            onUninstallClick(app) 
        }
    }

    override fun getItemCount(): Int = appList.size

    private fun Int.toPx(context: android.content.Context): Int {
        return (this * context.resources.displayMetrics.density).toInt()
    }
}
