package com.chick_mood.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.chick_mood.data.model.Emotion
import com.chick_mood.data.model.MoodRecord
import com.daodaoshi.chick_mood.R
import com.daodaoshi.chick_mood.ImageUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import android.util.Log

/**
 * 心情记录适配器 - 用于ViewPager2横向展示历史心情记录
 *
 * 支持三种内容状态：
 * 1. 纯文本 - 只显示文字内容
 * 2. 文本+图片 - 显示文字内容和一张图片
 * 3. 多图+文本 - 显示文字内容和多张图片网格
 *
 * @author Claude
 * @date 2025-10-23
 */
class MoodRecordAdapter(
    private var moodRecords: List<MoodRecord> = emptyList(),
    private val onItemClick: (MoodRecord) -> Unit = {},
    private val onFavoriteClick: (MoodRecord) -> Unit = {},
    private val onShareClick: (MoodRecord) -> Unit = {},
    private val onDetailClick: (MoodRecord) -> Unit = {}
) : RecyclerView.Adapter<MoodRecordAdapter.MoodRecordViewHolder>() {

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

    /**
     * 更新数据集
     */
    fun updateData(newRecords: List<MoodRecord>) {
        val oldSize = moodRecords.size
        moodRecords = newRecords
        val newSize = newRecords.size

        when {
            oldSize == 0 && newSize > 0 -> {
                notifyItemRangeInserted(0, newSize)
            }
            oldSize > 0 && newSize == 0 -> {
                notifyItemRangeRemoved(0, oldSize)
            }
            else -> {
                notifyDataSetChanged()
            }
        }
    }

    /**
     * 获取当前数据集
     */
    fun getData(): List<MoodRecord> = moodRecords

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

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

    override fun getItemCount(): Int = moodRecords.size

    inner class MoodRecordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        // 时间相关
        private val tvWeekday: TextView = itemView.findViewById(R.id.tv_weekday)
        private val tvDatetime: TextView = itemView.findViewById(R.id.tv_datetime)

        // 内容相关
        private val ivChickMood: ImageView = itemView.findViewById(R.id.iv_chick_mood)
        private val tvMoodContent: TextView = itemView.findViewById(R.id.tv_mood_content)
        private val ivSingleImage: ImageView = itemView.findViewById(R.id.iv_single_image)
        private val llMultiImages: LinearLayout = itemView.findViewById(R.id.ll_multi_images)
        private val ivImage1: ImageView = itemView.findViewById(R.id.iv_image1)
        private val ivImage2: ImageView = itemView.findViewById(R.id.iv_image2)
        private val ivImage3: ImageView = itemView.findViewById(R.id.iv_image3)

        // 操作按钮
        private val btnFavorite: LinearLayout = itemView.findViewById(R.id.btn_favorite)
        private val btnShare: LinearLayout = itemView.findViewById(R.id.btn_share)
        private val btnDetail: LinearLayout = itemView.findViewById(R.id.btn_detail)
        private val ivFavorite: ImageView = itemView.findViewById(R.id.iv_favorite)

        fun bind(record: MoodRecord) {
            // 设置时间显示
            setTimeDisplay(record.timestamp)

            // 设置小鸡形象
            setChickImage(record.emotion)

            // 设置心情内容
            setContentDisplay(record)

            // 设置收藏状态
            setFavoriteState(record.isFavorite)

            // 设置点击事件
            setClickListeners(record)
        }

        /**
         * 设置时间显示
         */
        private fun setTimeDisplay(timestamp: Long) {
            val nowCalendar = java.util.Calendar.getInstance()
            val recordCalendar = java.util.Calendar.getInstance()
            recordCalendar.timeInMillis = timestamp

            // 获取两个日期的开始时间（午夜00:00:00）
            val nowStartOfDay = getStartOfDay(nowCalendar)
            val recordStartOfDay = getStartOfDay(recordCalendar)

            // 计算日期差（天数）
            val daysDiff = (nowStartOfDay - recordStartOfDay) / (24 * 60 * 60 * 1000)

            val weekday = when (daysDiff.toInt()) {
                0 -> "今天"
                1 -> "昨天"
                else -> {
                    when (recordCalendar.get(java.util.Calendar.DAY_OF_WEEK)) {
                        java.util.Calendar.MONDAY -> "星期一"
                        java.util.Calendar.TUESDAY -> "星期二"
                        java.util.Calendar.WEDNESDAY -> "星期三"
                        java.util.Calendar.THURSDAY -> "星期四"
                        java.util.Calendar.FRIDAY -> "星期五"
                        java.util.Calendar.SATURDAY -> "星期六"
                        java.util.Calendar.SUNDAY -> "星期日"
                        else -> "未知"
                    }
                }
            }

            tvWeekday.text = weekday

            val dateFormat = java.text.SimpleDateFormat("yyyy.MM.dd HH:mm", java.util.Locale.getDefault())
            tvDatetime.text = dateFormat.format(java.util.Date(timestamp))
        }

        /**
         * 获取指定日期的开始时间（午夜00:00:00的时间戳）
         */
        private fun getStartOfDay(calendar: java.util.Calendar): Long {
            val copy = calendar.clone() as java.util.Calendar
            copy.set(java.util.Calendar.HOUR_OF_DAY, 0)
            copy.set(java.util.Calendar.MINUTE, 0)
            copy.set(java.util.Calendar.SECOND, 0)
            copy.set(java.util.Calendar.MILLISECOND, 0)
            return copy.timeInMillis
        }

        /**
         * 设置小鸡形象
         */
        private fun setChickImage(emotion: Emotion) {
            val chickResId = when (emotion) {
                Emotion.HAPPY -> R.drawable.ic_placeholder_chick_happy
                Emotion.SAD -> R.drawable.ic_placeholder_chick_sad
                Emotion.ANGRY -> R.drawable.ic_placeholder_chick_angry
                Emotion.WORRIED -> R.drawable.ic_placeholder_chick_worried
                Emotion.LONELY -> R.drawable.ic_placeholder_chick_lonely
                Emotion.SCARED -> R.drawable.ic_placeholder_chick_scared
            }
            ivChickMood.setImageResource(chickResId)
        }

        /**
         * 设置内容显示
         */
        private fun setContentDisplay(record: MoodRecord) {
            // 重置所有内容视图的可见性
            tvMoodContent.visibility = View.GONE
            ivSingleImage.visibility = View.GONE
            llMultiImages.visibility = View.GONE

            // 设置文本内容
            if (!record.textContent.isNullOrBlank()) {
                tvMoodContent.text = record.textContent
                tvMoodContent.visibility = View.VISIBLE
            }

            // 设置图片内容 - 当前模型只支持单张图片
            if (record.hasImage()) {
                ivSingleImage.visibility = View.VISIBLE
                // 加载实际图片
                loadImageFromPath(record.imagePath)
            }
        }

        /**
         * 设置收藏状态
         */
        private fun setFavoriteState(isFavorite: Boolean) {
            val favoriteResId = if (isFavorite) {
                R.drawable.ic_favorite_filled // 需要创建填充版本的收藏图标
            } else {
                R.drawable.ic_favorite_border
            }
            ivFavorite.setImageResource(favoriteResId)
        }

        /**
         * 设置点击事件
         */
        private fun setClickListeners(record: MoodRecord) {
            // 整个卡片点击
            itemView.setOnClickListener {
                onItemClick(record)
            }

            // 收藏按钮点击
            btnFavorite.setOnClickListener {
                onFavoriteClick(record)
            }

            // 分享按钮点击
            btnShare.setOnClickListener {
                onShareClick(record)
            }

            // 详情按钮点击
            btnDetail.setOnClickListener {
                onDetailClick(record)
            }
        }

        /**
         * 从文件路径加载图片
         */
        private fun loadImageFromPath(imagePath: String?) {
            imagePath?.let { path ->
                CoroutineScope(Dispatchers.IO).launch {
                    val bitmap = ImageUtils.loadBitmapFromPath(path)

                    withContext(Dispatchers.Main) {
                        if (bitmap != null) {
                            ivSingleImage.setImageBitmap(bitmap)
                            Log.d("MoodRecordAdapter", "卡片图片加载成功: $path")
                        } else {
                            // 如果加载失败，使用占位图
                            ivSingleImage.setImageResource(R.drawable.placeholder_background)
                            Log.w("MoodRecordAdapter", "卡片图片加载失败，使用占位图: $path")
                        }
                    }
                }
            }
        }
    }
}