package com.example.myapplication.ui.keyboard

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bumptech.glide.Glide
import com.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.SubjectTag
import com.example.myapplication.network.themeDetail
import com.example.myapplication.network.purchaseThemeRequest
import com.example.myapplication.ui.shop.ThemeCardAdapter
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.imageview.ShapeableImageView
import kotlinx.coroutines.launch
import com.example.myapplication.GuideActivity
import com.example.myapplication.network.themeStyle
import com.example.myapplication.network.FileDownloader
import com.example.myapplication.theme.ThemeManager
import com.example.myapplication.utils.unzipThemeSmart
import com.example.myapplication.utils.logZipEntries
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedInputStream
import java.io.FileInputStream

class KeyboardDetailFragment : Fragment() {

    private lateinit var shapeableImageView: ShapeableImageView
    private lateinit var tvKeyboardName: TextView
    private lateinit var tvDownloadCount: TextView
    private lateinit var layoutTagsContainer: LinearLayout
    private lateinit var recyclerRecommendList: RecyclerView
    private lateinit var themeCardAdapter: ThemeCardAdapter
    private lateinit var tvPrice: TextView
    private lateinit var rechargeButton: LinearLayout
    private lateinit var enabledButton: LinearLayout
    private lateinit var enabledButtonText: TextView
    private lateinit var progressBar: android.widget.ProgressBar
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.keyboard_detail, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        shapeableImageView = view.findViewById<ShapeableImageView>(R.id.iv_keyboard)
        tvKeyboardName = view.findViewById<TextView>(R.id.tv_keyboard_name)
        tvDownloadCount = view.findViewById<TextView>(R.id.tv_download_count)
        layoutTagsContainer = view.findViewById<LinearLayout>(R.id.layout_tags_container)
        recyclerRecommendList = view.findViewById<RecyclerView>(R.id.recycler_recommend_list)
        tvPrice = view.findViewById<TextView>(R.id.tv_price)
        rechargeButton = view.findViewById<LinearLayout>(R.id.rechargeButton)
        enabledButton = view.findViewById<LinearLayout>(R.id.enabledButton)
        enabledButtonText = view.findViewById<TextView>(R.id.enabledButtonText)
        progressBar = view.findViewById<android.widget.ProgressBar>(R.id.progressBar)
        swipeRefreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout)
        
        // 设置按钮始终防止事件穿透的触摸监听器
        enabledButton.setOnTouchListener { _, event ->
            // 如果按钮被禁用，消耗所有触摸事件防止穿透
            if (!enabledButton.isEnabled) {
                return@setOnTouchListener true
            }
            // 如果按钮启用，不消耗事件，让按钮正常处理点击
            return@setOnTouchListener false
        }
        
        // 初始化RecyclerView
        setupRecyclerView()

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener {
            loadData()
        }

        // 获取传递的参数
        val themeId = arguments?.getInt("themeId", 0) ?: 0
        
        // 根据themeId加载主题详情
        if (themeId != 0) {
            loadData()
        }
        
        view.findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
            parentFragmentManager.popBackStack()
        }
        
        //充值主题
        rechargeButton.setOnClickListener {
            showPurchaseConfirmationDialog(themeId)
        }
        //启动主题
        enabledButton.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                enableTheme()
            }
        }
    }

    private fun loadData() {
        val themeId = arguments?.getInt("themeId", 0) ?: 0
        if (themeId == 0) {
            swipeRefreshLayout.isRefreshing = false
            return
        }
        
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val themeDetailResp = getThemeDetail(themeId)?.data
                val recommendThemeListResp = getrecommendThemeList()?.data

                Glide.with(requireView().context)
                    .load(themeDetailResp?.themePreviewImageUrl)
                    .placeholder(R.drawable.bg)
                    .into(shapeableImageView)

                tvKeyboardName.text = themeDetailResp?.themeName
                tvDownloadCount.text = "Download:${themeDetailResp?.themeDownload}"
                tvPrice.text = "${themeDetailResp?.themePrice}"

                if (themeDetailResp?.isPurchased ?: false) {
                    rechargeButton.visibility = View.GONE
                    enabledButton.visibility = View.VISIBLE
                } else {
                    rechargeButton.visibility = View.VISIBLE
                    enabledButton.visibility = View.GONE
                }

                // 渲染标签
                themeDetailResp?.themeTag?.let { tags ->
                    renderTags(tags)
                }
                
                // 渲染推荐主题列表（剔除当前themeId）
                recommendThemeListResp?.let { themes ->
                    val filteredThemes = themes.filter { it.id != themeId }
                    themeCardAdapter.submitList(filteredThemes)
                }
                
            } catch (e: Exception) {
                Log.e("KeyboardDetailFragment", "获取主题详情异常", e)
            } finally {
                // 停止刷新动画
                swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    private fun renderTags(tags: List<SubjectTag>) {
        layoutTagsContainer.removeAllViews()
        
        if (tags.isEmpty()) return
        
        val context = layoutTagsContainer.context
        val tagsPerRow = 5 // 每行固定显示5个标签
        
        // 将标签分组，每行6个
        val rows = tags.chunked(tagsPerRow)
        
        rows.forEach { rowTags ->
            val rowLayout = LinearLayout(context).apply {
                orientation = LinearLayout.HORIZONTAL
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    // 添加行间距：上下相隔5dp
                    bottomMargin = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 5f, resources.displayMetrics
                    ).toInt()
                }
            }
            
            // 计算每个标签的权重（等间距分布）
            val tagWeight = 1f / tagsPerRow
            
            rowTags.forEach { tag ->
                val tagView = TextView(context).apply {
                    text = tag.label
                    setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
                    setTextColor(ContextCompat.getColor(context, android.R.color.white))
                    gravity = Gravity.CENTER
                    
                    // 设置内边距：左右12dp，上下5dp
                    val horizontalPadding = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 12f, resources.displayMetrics
                    ).toInt()
                    val verticalPadding = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 5f, resources.displayMetrics
                    ).toInt()
                    setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
                    
                    // 设置背景（50dp圆角）
                    background = ContextCompat.getDrawable(context, R.drawable.tag_background)?.mutate()
                    background?.setTint(android.graphics.Color.parseColor(tag.color))
                }
                
                // 使用权重布局，让标签自适应间距
                val layoutParams = LinearLayout.LayoutParams(
                    0, // 宽度设为0，使用权重
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    tagWeight
                ).apply {
                    // 添加标签间距
                    marginEnd = TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP, 8f, resources.displayMetrics
                    ).toInt()
                }
                
                rowLayout.addView(tagView, layoutParams)
            }
            
            // 如果当前行标签数量不足6个，添加空View填充剩余空间
            val remainingTags = tagsPerRow - rowTags.size
            if (remainingTags > 0) {
                repeat(remainingTags) {
                    val emptyView = View(context)
                    val layoutParams = LinearLayout.LayoutParams(
                        0, // 宽度设为0，使用权重
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        tagWeight
                    ).apply {
                        marginEnd = TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP, 8f, resources.displayMetrics
                        ).toInt()
                    }
                    rowLayout.addView(emptyView, layoutParams)
                }
            }
            
            layoutTagsContainer.addView(rowLayout)
        }
    }
    //=============================网络请求===================================
    private suspend fun getThemeDetail(themeId: Int): ApiResponse<themeDetail>? {
        return try {
            RetrofitClient.apiService.themeDetail(themeId)
        } catch (e: Exception) {
            Log.e("KeyboardDetailFragment", "获取主题详情失败", e)
            null
        }
    }

    private suspend fun setrestoreTheme(themeId: Int): ApiResponse<Unit>? {
        return try {
            RetrofitClient.apiService.restoreTheme(themeId)
        } catch (e: Exception) {
            Log.e("KeyboardDetailFragment", "恢复已删除的主题失败", e)
            null
        }
    }

    private suspend fun getrecommendThemeList(): ApiResponse<List<themeStyle>>? {
        return try {
            RetrofitClient.apiService.recommendThemeList()
        } catch (e: Exception) {
            Log.e("KeyboardDetailFragment", "获取推荐列表失败", e)
            null
        }
    }
    private suspend fun setpurchaseTheme(purchaseId: Int) {
        try {
            val purchaseThemeRequest = purchaseThemeRequest(themeId = purchaseId)
            val response = RetrofitClient.apiService.purchaseTheme(purchaseThemeRequest)
            
            // 购买成功后触发刷新（成功状态码为0）
            if (response?.code == 0) {
                loadData()
            }
        } catch (e: Exception) {
            Log.e("KeyboardDetailFragment", "购买主题失败", e)
        }
    }


    //=============================RecyclerView===================================
    private fun setupRecyclerView() {
        // 设置GridLayoutManager，每行显示2个item
        val layoutManager = GridLayoutManager(requireContext(), 2)
        recyclerRecommendList.layoutManager = layoutManager
        
        // 初始化ThemeCardAdapter
        themeCardAdapter = ThemeCardAdapter()
        recyclerRecommendList.adapter = themeCardAdapter
        
        // 设置item间距（可选）
        recyclerRecommendList.setPadding(0, 0, 0, 0)
    }
    
    //=============================弹窗===================================
    private fun showPurchaseConfirmationDialog(themeId: Int) {
        val dialog = Dialog(requireContext())
        dialog.setContentView(R.layout.dialog_purchase_confirmation)
        
        // 设置弹窗属性
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.window?.setLayout(
            android.view.WindowManager.LayoutParams.WRAP_CONTENT,
            android.view.WindowManager.LayoutParams.WRAP_CONTENT
        )
        
        // 设置按钮点击事件
        dialog.findViewById<TextView>(R.id.btn_confirm).setOnClickListener {
            // 确认购买逻辑
            viewLifecycleOwner.lifecycleScope.launch {
                setpurchaseTheme(themeId)
                dialog.dismiss()
            }
        }
        
        dialog.findViewById<TextView>(R.id.btn_cancel).setOnClickListener {
            dialog.dismiss()
        }
        
        // 显示弹窗
        dialog.show()
    }
    
    /**
     * 从 URL 中提取 zip 包名（去掉路径和查询参数，去掉 .zip 扩展名）
     */
    private fun extractZipNameFromUrl(url: String): String {
        // 提取文件名部分（去掉路径和查询参数）
        val fileName = if (url.contains('?')) {
            url.substring(url.lastIndexOf('/') + 1, url.indexOf('?'))
        } else {
            url.substring(url.lastIndexOf('/') + 1)
        }
        
        // 去掉 .zip 扩展名
        return if (fileName.endsWith(".zip")) {
            fileName.substring(0, fileName.length - 4)
        } else {
            fileName
        }
    }
    
    /**
     * 启用主题：下载、解压并设置主题
     */
    private suspend fun enableTheme() {
        val themeId = arguments?.getInt("themeId", 0) ?: 0
        if (themeId == 0) {
            return
        }
        
        // 恢复已删除的主题
        val restoreResponse = setrestoreTheme(themeId)
        if (restoreResponse?.code != 0) {
            // 恢复失败，显示错误信息并返回
            Log.e("1314520-KeyboardDetailFragment", "恢复主题失败: ${restoreResponse?.message ?: "未知错误"}")
            return
        }
        
        // 显示下载进度
        showDownloadProgress()
        
        try {
            // 获取主题详情
            val themeDetailResp = getThemeDetail(themeId)?.data
            if (themeDetailResp == null) {
                hideDownloadProgress()
                return
            }
            
            val downloadUrl = themeDetailResp.themeDownloadUrl
            
            if (downloadUrl.isNullOrEmpty()) {
                hideDownloadProgress()
                return
            }
            
            // 从下载 URL 中提取 zip 包名作为主题名称
            val themeName = extractZipNameFromUrl(downloadUrl)
            
            val context = requireContext()
            
            // 检查主题是否已存在
            val availableThemes = ThemeManager.listAvailableThemes(context)
            if (availableThemes.contains(themeId.toString())) {
                ThemeManager.setCurrentTheme(context, themeId.toString())
                showSuccessMessage("主题已启用")
                hideDownloadProgress()
                // 跳转到GuideActivity
                val intent = Intent(requireContext(), GuideActivity::class.java)
                startActivity(intent)
                return
            }
            
            // 主动下载主题 
            Log.d("1314520-KeyboardDetailFragment", "Downloading theme $themeName from $downloadUrl")
            
            // 下载 zip 文件
            val downloadedFile = FileDownloader.downloadZipFile(
                context = context,
                remoteFileName = downloadUrl,
                localFileName = "$themeName.zip"
            )
            
            if (downloadedFile == null) {
                showErrorMessage("下载主题失败")
                hideDownloadProgress()
                return
            }
            Log.d("1314520-zip", "path=${downloadedFile.absolutePath}")
            Log.d("1314520-zip", "size=${downloadedFile.length()} bytes")

            // 打印前16字节（确认PK头/或者错误文本）
            FileInputStream(downloadedFile).use { fis ->
                val head = ByteArray(16)
                val n = fis.read(head)
                Log.d("1314520-zip", "head16=${head.take(n).joinToString { b -> "%02X".format(b) }}")
            }
            
            // 解压到主题目录
            try {
                val installedThemeName: String = withContext(Dispatchers.IO) {
                    unzipThemeSmart(
                        context = context,
                        zipFile = downloadedFile,
                        themeId = themeId
                    )
                }
                ThemeManager.setCurrentTheme(context, installedThemeName)
                
                // 删除临时下载文件
                downloadedFile.delete()
                showSuccessMessage("主题启用成功")
                // 跳转到GuideActivity
                val intent = Intent(requireContext(), GuideActivity::class.java)
                startActivity(intent)
                
            } catch (e: Exception) {
                showErrorMessage("解压主题失败：${e.message}")
                // 清理临时文件
                downloadedFile.delete()
            }
            
        } catch (e: Exception) {
            showErrorMessage("启用主题失败")
        } finally {
            hideDownloadProgress()
        }
    }
    
    /**
     * 显示下载进度
     */
    private fun showDownloadProgress() {
        // 在主线程中更新UI
        view?.post {
            progressBar.visibility = View.VISIBLE
            enabledButtonText.text = "Loading..."
            // 完全禁用按钮交互
            enabledButton.isEnabled = false
            enabledButton.isClickable = false
            enabledButton.isFocusable = false
            // 防止点击事件穿透 - 消耗所有触摸事件
            enabledButton.setOnTouchListener { _, _ -> true }
            // 添加视觉上的禁用效果
            enabledButton.alpha = 0.6f
        }
    }
    
    /**
     * 隐藏下载进度
     */
    private fun hideDownloadProgress() {
        // 在主线程中更新UI
        view?.post {
            progressBar.visibility = View.GONE
            enabledButtonText.text = "Enabled"
            // 恢复按钮交互
            enabledButton.isEnabled = true
            enabledButton.isClickable = true
            enabledButton.isFocusable = true
            // 移除触摸监听器，恢复正常触摸事件处理
            enabledButton.setOnTouchListener(null)
            // 恢复正常的视觉效果
            enabledButton.alpha = 1.0f
        }
        
    }
    
    private fun showSuccessMessage(message: String) {
        // 使用 Toast 显示成功消息
        android.widget.Toast.makeText(requireContext(), message, android.widget.Toast.LENGTH_SHORT).show()
        Log.d("1314520-KeyboardDetailFragment", "Success: $message")
    }
    
    private fun showErrorMessage(message: String) {
        // 使用 Toast 显示错误消息
        android.widget.Toast.makeText(requireContext(), message, android.widget.Toast.LENGTH_SHORT).show()
        Log.e("1314520-KeyboardDetailFragment", "Error: $message")
    }
}
