package com.daodaoshi.chick_mood

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
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 EditActivity : AppCompatActivity() {

    private lateinit var backButton: ImageView
    private lateinit var timeText: TextView
    private lateinit var chickImage: ImageView
    private lateinit var moodValueText: TextView
    private lateinit var moodText: TextView
    private lateinit var textInput: EditText
    private lateinit var charCountText: TextView
    private lateinit var imageContainer: View
    private lateinit var imagePreviewContainer: FrameLayout
    private lateinit var imagePreview: ImageView
    private lateinit var addImageButton: View
    private lateinit var removeImageButton: ImageView
    private lateinit var saveButton: TextView

    private var currentRecord: MoodRecord? = null
    private var originalText: String = ""
    private var originalImagePath: String? = null
    private var currentImagePath: String? = null
    private val databaseManager = SimpleDatabaseManager.getInstance(this)

    // 图片选择器
    private val imagePickerLauncher = registerForActivityResult(
        androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.data?.let { uri ->
                // 处理选中的图片URI，保存到应用私有存储
                handleImageSelection(uri)
            }
        }
    }

    companion object {
        private const val MAX_TEXT_LENGTH = 500
        private const val TAG = "EditActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "EditActivity onCreate started")

        setContentView(R.layout.activity_edit)
        Log.d(TAG, "Layout set successfully")

        try {
            initViews()
            Log.d(TAG, "Views initialized")

            loadData()
            Log.d(TAG, "Data loading started")

            setupClickListeners()
            setupTextWatcher()
            Log.d(TAG, "Listeners setup completed")
        } catch (e: Exception) {
            Log.e(TAG, "Error in onCreate", e)
            showToast("初始化失败")
            finish()
        }
    }

    /**
     * 初始化视图组件
     */
    private fun initViews() {
        try {
            backButton = findViewById(R.id.back_button)
            timeText = findViewById(R.id.time_text)
            chickImage = findViewById(R.id.chick_image)
            moodValueText = findViewById(R.id.mood_value_text)
            moodText = findViewById(R.id.mood_text)
            textInput = findViewById(R.id.text_input)
            charCountText = findViewById(R.id.char_count_text)
            imageContainer = findViewById(R.id.image_container)
            imagePreviewContainer = findViewById(R.id.image_preview)
            imagePreview = findViewById(R.id.preview_image)
            addImageButton = findViewById(R.id.add_image_button)
            removeImageButton = findViewById(R.id.remove_image_button)
            saveButton = findViewById(R.id.save_button)
            Log.d(TAG, "All views found successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error initializing views", e)
            throw e
        }
    }

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

        loadRecordFromDatabase(recordId)
    }

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

                withContext(Dispatchers.Main) {
                    if (record != null) {
                        currentRecord = record
                        originalText = record.textContent ?: ""
                        originalImagePath = record.imagePath
                        currentImagePath = record.imagePath
                        displayRecord(record)
                        setupImageState()
                    } else {
                        showToast("记录不存在")
                        finish()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    showToast("加载记录失败")
                    finish()
                }
            }
        }
    }

    /**
     * 显示心情记录
     */
    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)

        // 设置文本内容
        textInput.setText(record.textContent ?: "")
        updateCharCount()

        // 图片状态在setupImageState中处理
    }

    /**
     * 设置图片状态
     */
    private fun setupImageState() {
        if (currentImagePath != null) {
            // 有图片状态
            addImageButton.visibility = View.GONE
            imagePreviewContainer.visibility = View.VISIBLE
            removeImageButton.visibility = View.VISIBLE
            Log.d(TAG, "设置有图片状态，图片路径: $currentImagePath")
            // 加载实际图片
            val imagePath = currentImagePath ?: ""
            loadImage(imagePath)
        } else {
            // 无图片状态
            addImageButton.visibility = View.VISIBLE
            imagePreviewContainer.visibility = View.GONE
            removeImageButton.visibility = View.GONE
            Log.d(TAG, "设置无图片状态")
        }
    }

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

        addImageButton.setOnClickListener {
            pickImageFromGallery()
        }

        removeImageButton.setOnClickListener {
            removeImage()
        }

        imagePreview.setOnClickListener {
            currentImagePath?.let { previewImage(it) }
        }

        saveButton.setOnClickListener {
            saveRecord()
        }
    }

    /**
     * 设置文本监听器
     */
    private fun setupTextWatcher() {
        textInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                updateCharCount()
            }

            override fun afterTextChanged(s: Editable?) {
                // 检查文本是否超过最大长度
                if (s != null && s.length > MAX_TEXT_LENGTH) {
                    textInput.setText(s.substring(0, MAX_TEXT_LENGTH))
                    textInput.setSelection(MAX_TEXT_LENGTH)
                }
            }
        })
    }

    /**
     * 更新字符计数
     */
    private fun updateCharCount() {
        val currentLength = textInput.text?.length ?: 0
        charCountText.text = "$currentLength/$MAX_TEXT_LENGTH"

        // 超过限制时显示红色警告
        if (currentLength > MAX_TEXT_LENGTH) {
            charCountText.setTextColor(getColor(R.color.error_color))
        } else {
            charCountText.setTextColor(getColor(R.color.text_secondary))
        }
    }

    /**
     * 处理返回键点击
     */
    private fun handleBackPressed() {
        if (hasUnsavedChanges()) {
            showExitConfirmDialog()
        } else {
            finish()
        }
    }

    /**
     * 检查是否有未保存的更改
     */
    private fun hasUnsavedChanges(): Boolean {
        val currentText = textInput.text?.toString() ?: ""
        return currentText != originalText || currentImagePath != originalImagePath
    }

    /**
     * 显示退出确认对话框
     */
    private fun showExitConfirmDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_exit_edit_confirm, null)
        val dialog = android.app.AlertDialog.Builder(this)
            .setView(dialogView)
            .create()

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

        val tvContinueEdit = dialogView.findViewById<TextView>(R.id.tv_continue_edit)
        val tvExit = dialogView.findViewById<TextView>(R.id.tv_exit)

        tvContinueEdit.setOnClickListener {
            dialog.dismiss()
        }

        tvExit.setOnClickListener {
            dialog.dismiss()
            finish()
        }

        dialog.show()
    }

    /**
     * 从相册选择图片
     */
    private fun pickImageFromGallery() {
        try {
            val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
                type = "image/*"
                putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/jpeg", "image/png"))
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
            }
            imagePickerLauncher.launch(intent)
        } catch (e: Exception) {
            showToast("无法打开相册")
        }
    }

    /**
     * 移除图片
     */
    private fun removeImage() {
        // 先删除图片文件
        removeImageFile()
        // 然后清空路径并更新UI
        currentImagePath = null
        setupImageState()
    }

    /**
     * 预览图片
     */
    private fun previewImage(imagePath: String) {
        val intent = Intent(this, ImagePreviewActivity::class.java).apply {
            putExtra("image_path", imagePath)
        }
        startActivity(intent)
    }

    /**
     * 保存记录
     */
    private fun saveRecord() {
        currentRecord?.let { record ->
            val updatedText = textInput.text?.toString()?.trim() ?: ""

            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val updatedRecord = record.copy(
                        textContent = if (updatedText.isEmpty()) null else updatedText,
                        imagePath = currentImagePath,
                        timestamp = record.timestamp  // 保持原始时间戳不变
                    )

                    databaseManager.updateMoodRecord(updatedRecord)

                    withContext(Dispatchers.Main) {
                        showToast("保存成功")

                        // 直接跳转到首页并传递编辑的记录ID用于定位
                        val homeIntent = Intent(this@EditActivity, MainActivitySimple::class.java).apply {
                            putExtra("edited_record_id", record.id)
                            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                        }
                        startActivity(homeIntent)
                        finish()
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        showToast("保存失败")
                    }
                }
            }
        }
    }

    /**
     * 格式化时间显示
     */
    private fun formatTime(timestamp: Long): String {
        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
        }
    }

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

    /**
     * 处理图片选择
     */
    private fun handleImageSelection(uri: android.net.Uri) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 将图片保存到应用私有存储
                val savedPath = ImageUtils.saveImageToInternalStorage(this@EditActivity, uri)

                withContext(Dispatchers.Main) {
                    if (savedPath != null) {
                        currentImagePath = savedPath
                        setupImageState()
                        Log.d(TAG, "图片保存成功: $savedPath")
                    } else {
                        showToast("保存图片失败")
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理图片选择失败", e)
                withContext(Dispatchers.Main) {
                    showToast("处理图片失败")
                }
            }
        }
    }

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

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

    /**
     * 移除图片文件
     */
    private fun removeImageFile() {
        currentImagePath?.let { path ->
            val success = ImageUtils.deleteImageFile(path)
            if (success) {
                Log.d(TAG, "图片文件删除成功: $path")
            } else {
                Log.w(TAG, "图片文件删除失败: $path")
            }
        }
    }

    override fun onBackPressed() {
        handleBackPressed()
    }
}