package com.daodaoshi.chick_mood

import android.os.Bundle
import android.util.Log
import android.animation.Animator
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.viewpager2.widget.ViewPager2
import com.daodaoshi.chick_mood.databinding.ActivityMainBinding
import com.chick_mood.data.database.DatabaseTestHelper
import com.chick_mood.data.database.SimpleDatabaseManager
import com.chick_mood.ui.emotion.EmotionSelectorDialog
import com.chick_mood.ui.adapter.MoodRecordAdapter
import com.chick_mood.data.model.Emotion
import com.chick_mood.data.model.MoodRecord
import java.text.SimpleDateFormat
import java.util.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 简化的首页Activity - 主要用于展示历史心情记录和创建新记录的入口
 *
 * 这个版本专注于验证基础功能，后续会逐步添加完整功能
 *
 * @author Claude
 * @date 2025-10-22
 */
class MainActivitySimple : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
        @JvmStatic
        lateinit var instance: MainActivitySimple
            private set
    }

    private lateinit var binding: ActivityMainBinding
    private lateinit var timeFormatter: SimpleDateFormat
    private lateinit var moodRecordAdapter: MoodRecordAdapter
    private var recordIdToLocate: Long = -1L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        instance = this

        // 初始化ViewBinding
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 初始化时间格式化器
        timeFormatter = SimpleDateFormat("yyyy.MM.dd E HH:mm", Locale.getDefault())

        // 初始化UI组件
        initViews()

        // 初始化ViewPager2适配器
        initMoodRecordAdapter()

        // 数据库测试已禁用，避免创建额外的测试记录
        // runDatabaseTest()

        // 创建测试数据（如果数据库为空）
        createTestDataIfNeeded()

        // 加载历史记录数据
        loadMoodRecords()

        // 检查是否有编辑完成返回的记录需要定位
        checkAndLocateEditedRecordFromIntent()
    }

    /**
     * 初始化UI组件和事件监听器
     */
    private fun initViews() {
        // 设置Toolbar
        setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            title = "" // 根据设计图，顶部中间没有标题
            setDisplayHomeAsUpEnabled(false)
            setDisplayShowHomeEnabled(false)
        }

        // 设置顶部按钮点击事件
        binding.btnMore.setOnClickListener {
            // 更多按钮 - 打开侧边抽屉
            showTemporaryMessage("更多功能 - 侧边抽屉待实现")
            Log.d(TAG, "点击了更多按钮")
        }

        binding.btnStatistics.setOnClickListener {
            // 统计按钮 - 跳转到统计页面
            showTemporaryMessage("统计页面 - 待实现")
            Log.d(TAG, "点击了统计按钮")
        }

        // 设置点击监听器
        binding.fabAddMood.setOnClickListener {
            // 显示情绪选择对话框
            showEmotionSelector()
        }

        // 设置空白状态区域的点击事件
        binding.llEmptyState.setOnClickListener {
            // 播放点击动画效果（暂时用Toast代替）
            showTemporaryMessage("小鸡被点击了！")
        }

        // 设置小鸡动画
        setupChickAnimation()
    }

    /**
     * 设置小鸡动画
     */
    private fun setupChickAnimation() {
        // 暂时跳过动画设置，因为当前布局使用静态ImageView
        // 等后续实现Lottie动画时再完善
    }

    /**
     * 播放点击动画
     */
    private fun playClickAnimation() {
        // 暂时跳过动画实现，后续添加Lottie动画时完善
        // 可以在这里添加简单的缩放动画等效果
    }

    /**
     * 显示情绪选择对话框
     */
    private fun showEmotionSelector() {
        val emotionDialog = EmotionSelectorDialog.create(this) { selectedEmotion ->
            // 处理情绪选择结果
            onEmotionSelected(selectedEmotion)
        }
        emotionDialog.show()
    }

    /**
     * 处理情绪选择结果
     */
    private fun onEmotionSelected(emotion: Emotion) {
        val emotionName = when (emotion) {
            Emotion.HAPPY -> "开心"
            Emotion.SAD -> "悲伤"
            Emotion.ANGRY -> "生气"
            Emotion.WORRIED -> "烦恼"
            Emotion.LONELY -> "孤单"
            Emotion.SCARED -> "害怕"
        }

        showTemporaryMessage("你选择了：$emotionName")

        // 创建一条测试记录来验证功能
        createMoodRecordWithEmotion(emotion)

        Log.d(TAG, "用户选择了情绪：$emotionName")
    }

    /**
     * 根据选择的情绪创建心情记录
     */
    private fun createMoodRecordWithEmotion(emotion: Emotion) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val sampleTexts = mapOf(
                    Emotion.HAPPY to "今天心情特别好！阳光明媚，工作顺利，一切都感觉很美好。",
                    Emotion.SAD to "今天有点失落，可能是天气的原因，希望明天会更好。",
                    Emotion.ANGRY to "今天遇到一些烦心事，心情不太好，需要时间平复一下。",
                    Emotion.WORRIED to "对未来有些担忧，但相信只要努力，一切都会好起来的。",
                    Emotion.LONELY to "感觉有点孤单，想念朋友和家人，希望他们一切都好。",
                    Emotion.SCARED to "今天遇到了一些挑战，有点害怕，但要勇敢面对。"
                )

                val text = sampleTexts[emotion] ?: "记录一下此刻的心情。"

                val newRecord = MoodRecord.createTestRecord(
                    emotion = emotion,
                    intensity = (30..90).random(),
                    text = text
                )

                val dbManager = SimpleDatabaseManager.getInstance(this@MainActivitySimple)
                val insertedId = dbManager.createMoodRecord(
                    emotion = newRecord.emotion,
                    intensity = newRecord.moodIntensity,
                    noteText = newRecord.textContent ?: "",
                    imagePaths = if (newRecord.imagePath != null) listOf(newRecord.imagePath) else emptyList()
                )

                withContext(Dispatchers.Main) {
                    // 设置需要定位的新记录ID
                    recordIdToLocate = insertedId
                    // 重新加载数据以显示新记录
                    loadMoodRecords()
                }

                Log.d(TAG, "创建了新的心情记录: ${emotion.name}")
            } catch (e: Exception) {
                Log.e(TAG, "创建心情记录失败", e)
                withContext(Dispatchers.Main) {
                    showTemporaryMessage("创建记录失败")
                }
            }
        }
    }

    /**
     * 更新时间指示器
     */
    private fun updateTimeIndicator(timestamp: Long) {
        // TODO: 实现时间更新功能 - 暂时注释掉
        // val formattedTime = timeFormatter.format(Date(timestamp))
        // binding.tvTimeIndicator.text = formattedTime
    }

    /**
     * 显示空白状态UI
     */
    private fun showEmptyStateUI() {
        binding.llEmptyState.isVisible = true
        // TODO: 其他视图状态设置 - 暂时注释掉
        // binding.vpHistoryRecords.isVisible = false
        // binding.tvTimeIndicator.isVisible = false
    }

    /**
     * 显示内容状态UI
     */
    private fun showContentStateUI() {
        binding.llEmptyState.isVisible = false
        // TODO: 其他视图状态设置 - 暂时注释掉
        // binding.vpHistoryRecords.isVisible = true
        // binding.tvTimeIndicator.isVisible = true

        // TODO: 设置ViewPager2数据
        // binding.vpHistoryRecords.adapter = null
    }

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

    /**
     * 运行数据库测试
     */
    private fun runDatabaseTest() {
        try {
            Log.d("MainActivity", "开始运行数据库测试...")
            DatabaseTestHelper.runDatabaseTests(this)
        } catch (e: Exception) {
            Log.e("MainActivity", "数据库测试运行失败", e)
        }
    }

    /**
     * 获取当前页面状态 - 用于测试
     * @return true表示显示空状态，false表示显示历史记录
     */
    fun isShowingEmptyState(): Boolean {
        return binding.llEmptyState.isVisible
    }

    override fun onResume() {
        super.onResume()
        // 每次返回首页时重新加载数据，确保显示最新的数据库状态
        loadMoodRecords()
    }

    /**
     * 初始化心情记录适配器
     */
    private fun initMoodRecordAdapter() {
        moodRecordAdapter = MoodRecordAdapter(
            onItemClick = { record ->
                // 点击记录卡片 - 跳转到详情页
                Log.d(TAG, "点击了心情记录: ${record.emotion}")
                showMoodRecordDetail(record)
            },
            onFavoriteClick = { record ->
                // 收藏/取消收藏
                toggleFavorite(record)
            },
            onShareClick = { record ->
                // 分享记录
                shareMoodRecord(record)
            },
            onDetailClick = { record ->
                // 查看详情
                showMoodRecordDetail(record)
            }
        )

        binding.vpHistoryRecords.adapter = moodRecordAdapter
        binding.vpHistoryRecords.orientation = ViewPager2.ORIENTATION_HORIZONTAL

        // 设置页面变化回调，用于更新时间指示器
        binding.vpHistoryRecords.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (position < moodRecordAdapter.itemCount) {
                    // 当有记录时，更新时间指示器显示当前选中记录的时间
                    // updateTimeIndicator(moodRecordAdapter.moodRecords[position].timestamp)
                }
            }
        })
    }

    /**
     * 加载心情记录数据
     */
    private fun loadMoodRecords() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val dbManager = SimpleDatabaseManager.getInstance(this@MainActivitySimple)
            val records = dbManager.getRecentMoodRecords(50) // 获取最近50条记录

                withContext(Dispatchers.Main) {
                    if (records.isEmpty()) {
                        showEmptyStateUI()
                    } else {
                        showContentStateUI()
                        moodRecordAdapter.updateData(records)

                        // 检查是否需要定位记录
                        checkAndLocateEditedRecord()
                    }
                }

                Log.d(TAG, "加载了 ${records.size} 条心情记录")
            } catch (e: Exception) {
                Log.e(TAG, "加载心情记录失败", e)
                withContext(Dispatchers.Main) {
                    showEmptyStateUI()
                    showTemporaryMessage("加载心情记录失败")
                }
            }
        }
    }

    /**
     * 切换收藏状态
     */
    private fun toggleFavorite(record: MoodRecord) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 创建更新后的记录（注意：这里需要修改数据模型支持更新）
                val updatedRecord = record.copy(isFavorite = !record.isFavorite)

                // TODO: 实现数据库更新功能
                // SimpleDatabaseManager.updateMoodRecord(updatedRecord)

                withContext(Dispatchers.Main) {
                    // 重新加载数据
                    loadMoodRecords()
                    val message = if (updatedRecord.isFavorite) "已收藏" else "已取消收藏"
                    showTemporaryMessage(message)
                }
            } catch (e: Exception) {
                Log.e(TAG, "切换收藏状态失败", e)
                withContext(Dispatchers.Main) {
                    showTemporaryMessage("操作失败")
                }
            }
        }
    }

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

        val shareText = buildString {
            if (record.textContent != null) {
                append(record.textContent)
                append("\n\n")
            }
            append("心情：$emotionName")
            append("\n时间：${record.getFormattedTime()}")
        }

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

    /**
     * 显示心情记录详情
     */
    private fun showMoodRecordDetail(record: MoodRecord) {
        try {
            val intent = android.content.Intent(this, DetailActivity::class.java).apply {
                putExtra("record_id", record.id)
            }
            startActivity(intent)
        } catch (e: Exception) {
            Log.e(TAG, "跳转详情页失败", e)
            showTemporaryMessage("打开详情页失败")
        }
    }

    /**
     * 创建测试心情记录（用于测试）
     */
    private fun createTestMoodRecord() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val testRecord = MoodRecord.createTestRecord(
                    emotion = Emotion.HAPPY,
                    intensity = 75,
                    text = "今天心情很不错！工作顺利，还和朋友聚餐了，感觉很充实。"
                )

                val dbManager = SimpleDatabaseManager.getInstance(this@MainActivitySimple)
                dbManager.createMoodRecord(
                    emotion = testRecord.emotion,
                    intensity = testRecord.moodIntensity,
                    noteText = testRecord.textContent ?: "",
                    imagePaths = if (testRecord.imagePath != null) listOf(testRecord.imagePath) else emptyList()
                )

                withContext(Dispatchers.Main) {
                    loadMoodRecords() // 重新加载数据
                    showTemporaryMessage("已添加测试记录")
                }

                Log.d(TAG, "创建了测试心情记录")
            } catch (e: Exception) {
                Log.e(TAG, "创建测试记录失败", e)
                withContext(Dispatchers.Main) {
                    showTemporaryMessage("创建测试记录失败")
                }
            }
        }
    }

    /**
     * 创建测试数据（如果数据库为空）
     */
    private fun createTestDataIfNeeded() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val dbManager = SimpleDatabaseManager.getInstance(this@MainActivitySimple)
                val recordCount = dbManager.getMoodRecordCount()

                if (recordCount == 0) {
                    // 数据库为空，创建一些测试数据
                    val testData = generateRealisticTestData()

                    for (data in testData) {
                        dbManager.createMoodRecord(
                            emotion = data.emotion,
                            intensity = data.moodIntensity,
                            noteText = data.textContent ?: "",
                            imagePaths = if (data.imagePath != null) listOf(data.imagePath) else emptyList()
                        )
                    }

                    Log.d(TAG, "创建了 ${testData.size} 条测试数据")
                }
            } catch (e: Exception) {
                Log.e(TAG, "创建测试数据失败", e)
            }
        }
    }

    /**
     * 生成真实的测试数据
     */
    private fun generateRealisticTestData(): List<MoodRecord> {
        val currentTime = System.currentTimeMillis()
        val oneDayMs = 24 * 60 * 60 * 1000L

        return listOf(
            MoodRecord(
                id = 0, // 数据库会自动生成ID
                emotion = Emotion.HAPPY,
                moodIntensity = 85,
                textContent = "今天心情特别好！阳光明媚，工作顺利，还和朋友聚餐了，感觉很充实。生活就是这样，简单的美好就让人很满足。",
                imagePath = "placeholder_image_1",
                timestamp = currentTime - 2 * oneDayMs,
                isFavorite = true
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.WORRIED,
                moodIntensity = 65,
                textContent = "工作上遇到了一些挑战，有点压力，但我相信能够克服。明天要好好规划一下时间。",
                imagePath = null,
                timestamp = currentTime - 3 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.ANGRY,
                moodIntensity = 75,
                textContent = "今天遇到了一些不愉快的事情，心情很糟糕。深呼吸，冷静下来，明天会是新的一天。",
                imagePath = null,
                timestamp = currentTime - 4 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.SAD,
                moodIntensity = 55,
                textContent = "今天有点失落，可能是天气的原因，也可能是因为想家了。希望明天会更好。",
                imagePath = "placeholder_image_2",
                timestamp = currentTime - 5 * oneDayMs,
                isFavorite = true
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.LONELY,
                moodIntensity = 70,
                textContent = "感觉有点孤单，想念朋友和家人。但这也是成长的一部分，学会独处也是一种能力。",
                imagePath = null,
                timestamp = currentTime - 6 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.HAPPY,
                moodIntensity = 95,
                textContent = "超级开心！收到了期待已久的好消息，所有的努力都值得了！",
                imagePath = "placeholder_image_3",
                timestamp = currentTime - 7 * oneDayMs,
                isFavorite = true
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.SCARED,
                moodIntensity = 45,
                textContent = "对未来的不确定性感到有些害怕，但我知道逃避不是解决方法。勇敢面对，一步一步来。",
                imagePath = null,
                timestamp = currentTime - 8 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.HAPPY,
                moodIntensity = 80,
                textContent = "",
                imagePath = "placeholder_image_4",
                timestamp = currentTime - 9 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.WORRIED,
                moodIntensity = 60,
                textContent = null,
                imagePath = null,
                timestamp = currentTime - 10 * oneDayMs,
                isFavorite = false
            ),
            MoodRecord(
                id = 0,
                emotion = Emotion.SAD,
                moodIntensity = 40,
                textContent = "今天没什么特别的心情，就是有点低落。听音乐放松一下吧。",
                imagePath = null,
                timestamp = currentTime - 11 * oneDayMs,
                isFavorite = false
            )
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: android.content.Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK) {
            // 处理编辑页面返回的结果
            data?.getLongExtra("edited_record_id", -1L)?.let { editedRecordId: Long ->
                if (editedRecordId != -1L) {
                    // 找到编辑的记录在列表中的位置并定位
                    locateRecordInList(editedRecordId)
                }
            }
        }
    }

    /**
     * 在列表中定位记录
     */
    private fun locateRecordInList(recordId: Long) {
        try {
            Log.d(TAG, "开始定位记录ID: $recordId")

            // 确保ViewPager2已经准备好
            binding.vpHistoryRecords.post {
                // 从适配器获取最新数据
                val records = moodRecordAdapter.getData()
                Log.d(TAG, "当前适配器数据量: ${records.size}")

                val position = records.indexOfFirst { record -> record.id == recordId }
                Log.d(TAG, "查找记录ID $recordId，找到位置: $position")

                if (position != -1 && position < moodRecordAdapter.itemCount) {
                    // 使用setCurrentItem定位，第二个参数为true表示平滑滚动
                    binding.vpHistoryRecords.setCurrentItem(position, true)
                    Log.d(TAG, "已定位到位置: $position")

                    // 延迟一点再次确认定位，确保定位成功
                    binding.vpHistoryRecords.postDelayed({
                        val currentPosition = binding.vpHistoryRecords.currentItem
                        Log.d(TAG, "定位后当前位置: $currentPosition")
                        if (currentPosition != position) {
                            Log.w(TAG, "定位可能不准确，尝试重新定位")
                            binding.vpHistoryRecords.setCurrentItem(position, true)
                        }
                    }, 300)
                } else {
                    Log.w(TAG, "未找到记录ID: $recordId，或位置超出范围")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "定位记录失败", e)
        }
    }

    /**
     * 检查是否有编辑完成返回的记录需要定位
     */
    private fun checkAndLocateEditedRecordFromIntent() {
        val editedRecordId = intent.getLongExtra("edited_record_id", -1L)
        if (editedRecordId != -1L) {
            Log.d(TAG, "检测到编辑完成的记录ID: $editedRecordId")
            recordIdToLocate = editedRecordId
        }
    }

    /**
     * 检查是否需要定位记录（在数据加载完成后调用）
     */
    private fun checkAndLocateEditedRecord() {
        if (recordIdToLocate != -1L) {
            Log.d(TAG, "开始定位记录ID: $recordIdToLocate")
            locateRecordInList(recordIdToLocate)
            recordIdToLocate = -1L // 重置
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // TODO: 清理资源 - 暂时注释掉
        // binding.chickAnimationView.cancelAnimation()
    }
}