package com.daodaoshi.chick_mood

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.chick_mood.data.database.SimpleDatabaseManager
import com.chick_mood.data.model.Emotion
import com.chick_mood.data.model.MoodRecord
import com.daodaoshi.chick_mood.ImageUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.*

/**
 * 心情记录详情页
 * 展示单条心情记录的完整信息，支持查看、编辑、收藏、分享、删除等操作
 */
class DetailActivity : AppCompatActivity() {

    private lateinit var backButton: ImageView
    private lateinit var timeText: TextView
    private lateinit var moreButton: ImageView
    private lateinit var chickImage: ImageView
    private lateinit var moodValueText: TextView
    private lateinit var moodText: TextView
    private lateinit var imageContent: ImageView
    private lateinit var textContent: TextView

    private var currentRecord: MoodRecord? = null
    private val databaseManager = SimpleDatabaseManager.getInstance(this)

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

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

        initViews()
        loadData()
        setupClickListeners()
    }

    /**
     * 初始化视图组件
     */
    private fun initViews() {
        backButton = findViewById(R.id.back_button)
        timeText = findViewById(R.id.time_text)
        moreButton = findViewById(R.id.more_button)
        chickImage = findViewById(R.id.chick_image)
        moodValueText = findViewById(R.id.mood_value_text)
        moodText = findViewById(R.id.mood_text)
        imageContent = findViewById(R.id.image_content)
        textContent = findViewById(R.id.text_content)
    }

    /**
     * 加载心情记录数据
     */
    private fun loadData() {
        val recordId = intent.getLongExtra("record_id", -1L)
        if (recordId == -1L) {
            finish()
            return
        }

        // 从数据库获取记录
        loadRecordFromDatabase(recordId)
    }

    /**
     * 显示心情记录
     */
    private fun displayRecord(record: MoodRecord) {
        // 设置时间显示
        timeText.text = formatTime(record.timestamp)

        // 设置小鸡形象
        chickImage.setImageResource(getEmotionIconResource(record.emotion))

        // 设置心情值和文案
        moodValueText.text = record.moodIntensity.toString()
        moodText.text = generateMoodText(record.moodIntensity, record.emotion)

        // 设置图片内容（如果有）
        if (record.imagePath != null) {
            imageContent.visibility = View.VISIBLE
            // 加载实际图片
            loadImage(record.imagePath)
        } else {
            imageContent.visibility = View.GONE
        }

        // 设置文本内容（如果有）
        if (!record.textContent.isNullOrBlank()) {
            textContent.visibility = View.VISIBLE
            textContent.text = record.textContent
        } else {
            textContent.visibility = View.GONE
        }
    }

    /**
     * 设置点击监听器
     */
    private fun setupClickListeners() {
        backButton.setOnClickListener {
            finish()
        }

        moreButton.setOnClickListener {
            showMoreOptions()
        }

        imageContent.setOnClickListener {
            // 点击图片跳转到预览页面
            currentRecord?.imagePath?.let { imagePath ->
                val intent = Intent(this, ImagePreviewActivity::class.java).apply {
                    putExtra("image_path", imagePath)
                }
                startActivity(intent)
            }
        }
    }

    /**
     * 显示更多操作选项
     */
    private fun showMoreOptions() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_more_options, null)
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.setCanceledOnTouchOutside(true)

        // 获取视图组件
        val llEdit = dialogView.findViewById<LinearLayout>(R.id.ll_edit)
        val llFavorite = dialogView.findViewById<LinearLayout>(R.id.ll_favorite)
        val llShare = dialogView.findViewById<LinearLayout>(R.id.ll_share)
        val llDelete = dialogView.findViewById<LinearLayout>(R.id.ll_delete)
        val ivFavoriteIcon = dialogView.findViewById<ImageView>(R.id.iv_favorite_icon)
        val tvFavoriteText = dialogView.findViewById<TextView>(R.id.tv_favorite_text)

        // 更新收藏状态UI
        updateFavoriteUI(ivFavoriteIcon, tvFavoriteText, currentRecord?.isFavorite == true)

        // 设置点击事件
        llEdit.setOnClickListener {
            dialog.dismiss()
            jumpToEditPage()
        }

        llFavorite.setOnClickListener {
            dialog.dismiss()
            toggleFavorite()
        }

        llShare.setOnClickListener {
            dialog.dismiss()
            shareMoodRecord()
        }

        llDelete.setOnClickListener {
            dialog.dismiss()
            showDeleteConfirmDialog()
        }

        dialog.show()
    }

    /**
     * 从数据库加载心情记录
     */
    private fun loadRecordFromDatabase(recordId: Long) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val record = databaseManager.getMoodRecord(recordId)

                withContext(Dispatchers.Main) {
                    if (record != null) {
                        currentRecord = record
                        displayRecord(record)
                    } else {
                        // 如果没有找到记录，显示提示并关闭页面
                        showToast("记录不存在")
                        finish()
                    }
                }
            } catch (e: Exception) {
                Log.e("DetailActivity", "加载记录失败", e)
                withContext(Dispatchers.Main) {
                    showToast("加载记录失败")
                    finish()
                }
            }
        }
    }

    
    /**
     * 格式化时间显示
     */
    private fun formatTime(timestamp: Long): String {
        val now = System.currentTimeMillis()
        val today = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }.timeInMillis

        val yesterday = today - 24 * 60 * 60 * 1000L

        val date = Date(timestamp)
        val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        val timeString = timeFormat.format(date)

        return when {
            timestamp >= today -> "今天 $timeString"
            timestamp >= yesterday -> "昨天 $timeString"
            else -> {
                val dateFormat = SimpleDateFormat("M月d日 HH:mm", Locale.getDefault())
                dateFormat.format(date)
            }
        }
    }

    /**
     * 生成心情文案
     */
    private fun generateMoodText(moodValue: Int, emotion: Emotion): String {
        val degree = when {
            moodValue <= 20 -> "有些"
            moodValue <= 40 -> "非常"
            moodValue <= 60 -> "超级"
            moodValue <= 80 -> "这也太"
            else -> "完全无法控制"
        }

        return "$degree ${emotion.displayName}"
    }

    /**
     * 获取情绪图标资源
     */
    private fun getEmotionIconResource(emotion: Emotion): Int {
        return when (emotion) {
            Emotion.HAPPY -> R.drawable.ic_emotion_happy
            Emotion.ANGRY -> R.drawable.ic_emotion_angry
            Emotion.SAD -> R.drawable.ic_emotion_sad
            Emotion.WORRIED -> R.drawable.ic_emotion_worried
            Emotion.LONELY -> R.drawable.ic_emotion_lonely
            Emotion.SCARED -> R.drawable.ic_emotion_scared
        }
    }

    /**
     * 更新收藏状态UI
     */
    private fun updateFavoriteUI(iconView: ImageView, textView: TextView, isFavorite: Boolean) {
        if (isFavorite) {
            iconView.setImageResource(R.drawable.ic_favorite_filled)
            textView.text = "取消收藏"
        } else {
            iconView.setImageResource(R.drawable.ic_favorite_border)
            textView.text = "收藏"
        }
    }

    /**
     * 切换收藏状态
     */
    private fun toggleFavorite() {
        currentRecord?.let { record ->
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val newFavoriteStatus = !record.isFavorite
                    val updatedRecord = record.copy(isFavorite = newFavoriteStatus)

                    // 更新数据库
                    databaseManager.updateMoodRecord(updatedRecord)

                    withContext(Dispatchers.Main) {
                        currentRecord = updatedRecord
                        val message = if (newFavoriteStatus) "已收藏" else "已取消收藏"
                        showToast(message)
                    }
                } catch (e: Exception) {
                    Log.e("DetailActivity", "更新收藏状态失败", e)
                    withContext(Dispatchers.Main) {
                        showToast("操作失败")
                    }
                }
            }
        }
    }

    /**
     * 分享心情记录
     */
    private fun shareMoodRecord() {
        currentRecord?.let { record ->
            val emotionName = when (record.emotion) {
                Emotion.HAPPY -> "开心"
                Emotion.SAD -> "悲伤"
                Emotion.ANGRY -> "生气"
                Emotion.WORRIED -> "烦恼"
                Emotion.LONELY -> "孤单"
                Emotion.SCARED -> "害怕"
            }

            val shareText = buildString {
                if (!record.textContent.isNullOrBlank()) {
                    append(record.textContent)
                    append("\n\n")
                }
                append("心情：$emotionName")
                append("\n心情值：${record.moodIntensity}")
                append("\n文案：${generateMoodText(record.moodIntensity, record.emotion)}")
                append("\n时间：${formatTime(record.timestamp)}")
            }

            try {
                val shareIntent = Intent().apply {
                    action = Intent.ACTION_SEND
                    type = "text/plain"
                    putExtra(Intent.EXTRA_TEXT, shareText)
                    putExtra(Intent.EXTRA_SUBJECT, "我的心情记录")
                }
                startActivity(Intent.createChooser(shareIntent, "分享心情记录"))
            } catch (e: Exception) {
                showToast("分享失败")
            }
        }
    }

    /**
     * 显示删除确认对话框
     */
    private fun showDeleteConfirmDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_delete_confirm, null)
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()

        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.setCanceledOnTouchOutside(false)

        val tvCancel = dialogView.findViewById<TextView>(R.id.tv_cancel)
        val tvConfirm = dialogView.findViewById<TextView>(R.id.tv_confirm)

        tvCancel.setOnClickListener {
            dialog.dismiss()
        }

        tvConfirm.setOnClickListener {
            dialog.dismiss()
            deleteMoodRecord()
        }

        dialog.show()
    }

    /**
     * 删除心情记录
     */
    private fun deleteMoodRecord() {
        currentRecord?.let { record ->
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    // 从数据库删除记录
                    databaseManager.deleteMoodRecord(record.id)

                    withContext(Dispatchers.Main) {
                        showToast("记录已删除")
                        finish() // 返回首页
                    }
                } catch (e: Exception) {
                    Log.e("DetailActivity", "删除记录失败", e)
                    withContext(Dispatchers.Main) {
                        showToast("删除失败")
                    }
                }
            }
        }
    }

    /**
     * 跳转到编辑页面
     */
    private fun jumpToEditPage() {
        currentRecord?.let { record ->
            try {
                val intent = Intent(this, EditActivity::class.java).apply {
                    putExtra("record_id", record.id)
                }
                startActivity(intent)
            } catch (e: Exception) {
                showToast("无法打开编辑页面")
            }
        }
    }

    /**
     * 显示Toast消息
     */
    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    /**
     * 加载并显示图片
     */
    private fun loadImage(imagePath: String) {
        CoroutineScope(Dispatchers.IO).launch {
            val bitmap = ImageUtils.loadBitmapFromPath(imagePath)

            withContext(Dispatchers.Main) {
                if (bitmap != null) {
                    imageContent.setImageBitmap(bitmap)
                    Log.d(TAG, "详情页图片加载成功: $imagePath")
                } else {
                    // 如果加载失败，使用占位图
                    imageContent.setImageResource(R.drawable.ic_placeholder_image)
                    Log.w(TAG, "详情页图片加载失败，使用占位图: $imagePath")
                }
            }
        }
    }
}