package com.example.myapplication.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.myapplication.R
import com.example.myapplication.network.themeStyle
import com.google.android.material.card.MaterialCardView

class ThemeCardAdapter : ListAdapter<themeStyle, ThemeCardAdapter.ThemeCardViewHolder>(DiffCallback) {

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

    override fun onBindViewHolder(holder: ThemeCardViewHolder, position: Int) {
        val theme = getItem(position)
        holder.bind(theme)
    }

    inner class ThemeCardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val themeImage: ImageView = itemView.findViewById(R.id.theme_image)
        private val themeName: TextView = itemView.findViewById(R.id.theme_name)
        private val themePrice: TextView = itemView.findViewById(R.id.theme_price)
        private val themeCard: CardView = itemView.findViewById(R.id.theme_card)

        fun bind(theme: themeStyle) {
            // 加载主题图片
            Glide.with(itemView.context)
                .load(theme.themePreviewImageUrl)
                .placeholder(R.drawable.bg)
                .into(themeImage)

            // 设置主题名称
            themeName.text = theme.themeName

            // 设置主题价格
            themePrice.text = theme.themePrice.toString()

             // 设置主题卡片点击事件
            themeCard.setOnClickListener {
                // 跳转到主题详情页并传递参数
                val bundle = Bundle().apply {
                    putInt("themeId", theme.id)
                }
                itemView.findNavController().navigate(R.id.action_global_keyboardDetailFragment, bundle)
            }
        }
    }

    companion object {
        private val DiffCallback = object : DiffUtil.ItemCallback<themeStyle>() {
            override fun areItemsTheSame(oldItem: themeStyle, newItem: themeStyle): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: themeStyle, newItem: themeStyle): Boolean {
                return oldItem == newItem
            }
        }
    }
}
