package com.example.myapplication.ui.shop.myskin

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
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.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.themeStyle
import com.example.myapplication.network.deleteThemeRequest
import kotlinx.coroutines.launch

class MySkin : Fragment() {

    private lateinit var adapter: MySkinAdapter
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.my_skin, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val tvEditor = view.findViewById<TextView>(R.id.tvEditor)
        val bottomBar = view.findViewById<View>(R.id.bottomEditBar)
        val tvSelectedCount = view.findViewById<TextView>(R.id.tvSelectedCount)
        val btnDelete = view.findViewById<TextView>(R.id.btnDelete)
        swipeRefreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout)

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

        // 设置刷新指示器颜色
        swipeRefreshLayout.setColorSchemeColors(
            Color.parseColor("#02BEAC"),
            Color.parseColor("#1B1F1A"),
            Color.parseColor("#9F9F9F")
        )

        // 返回
        view.findViewById<FrameLayout>(R.id.iv_close).setOnClickListener {
            parentFragmentManager.popBackStack()
        }

        val rv = view.findViewById<RecyclerView>(R.id.rvThemes)
        rv.layoutManager = GridLayoutManager(requireContext(), 2)

        adapter = MySkinAdapter(
            onItemClick = { /* 非编辑模式点击：进详情等 */ },
            onSelectionChanged = { count ->
                tvSelectedCount.text = "$count themes selected"
                btnDelete.isEnabled = count > 0
                btnDelete.alpha = if (count > 0) 1f else 0.4f
            }
        )
        rv.adapter = adapter

        fun showBottomBar() {
            bottomBar.visibility = View.VISIBLE
            bottomBar.translationY = bottomBar.height.toFloat()
            bottomBar.animate().translationY(0f).setDuration(160).start()
        }

        fun hideBottomBar() {
            bottomBar.animate()
                .translationY(bottomBar.height.toFloat())
                .setDuration(160)
                .withEndAction { bottomBar.visibility = View.GONE }
                .start()
        }

        // Editor：进/退编辑
        tvEditor.setOnClickListener {
            if (!adapter.editMode) {
                adapter.enterEditMode()
                tvEditor.text = "Exit editing"
                bottomBar.post { showBottomBar() } // post 确保有 height
            } else {
                adapter.exitEditMode()
                tvEditor.text = "Editor"
                hideBottomBar()
            }
        }

        // 删除按钮
        btnDelete.setOnClickListener {
            val ids = adapter.getSelectedIds()
            if (ids.isEmpty()) return@setOnClickListener

            viewLifecycleOwner.lifecycleScope.launch {
                val resp = batchDeleteThemes(ids)
                if (resp?.code == 0) {
                    // 删除本地主题文件
                    deleteLocalThemeFiles(ids)
                    
                    // 如果当前主题是被删除的主题之一，切换到默认主题
                    val currentTheme = com.example.myapplication.theme.ThemeManager.getCurrentThemeName()
                    if (currentTheme != null && ids.any { it.toString() == currentTheme }) {
                        com.example.myapplication.theme.ThemeManager.setCurrentTheme(requireContext(), "default")
                    }
                    
                    adapter.removeByIds(ids.toSet())
                    adapter.exitEditMode()
                    tvEditor.text = "Editor"
                    hideBottomBar()
                }
            }
        }

        // 初始加载数据
        loadInitialData()
    }

    private fun loadInitialData() {
        viewLifecycleOwner.lifecycleScope.launch {
            val resp = getPurchasedThemeList()
            adapter.submitList(resp?.data ?: emptyList())
        }
    }

    private fun refreshData() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val resp = getPurchasedThemeList()
                adapter.submitList(resp?.data ?: emptyList())
                Log.d("1314520-MySkin", "下拉刷新完成")
            } catch (e: Exception) {
                Log.e("1314520-MySkin", "下拉刷新失败", e)
            } finally {
                // 停止刷新动画
                swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    private suspend fun getPurchasedThemeList(): ApiResponse<List<themeStyle>>? {
        return try { RetrofitClient.apiService.purchasedThemeList() }
        catch (e: Exception) { Log.e("MySkin", "获取已购买主题失败", e); null }
    }

    private suspend fun batchDeleteThemes(themeIds: List<Int>): ApiResponse<Boolean>? {
        val request = deleteThemeRequest(
            themeIds = themeIds
        )
        return try { RetrofitClient.apiService.batchDeleteUserTheme(request) }
        catch (e: Exception) { Log.e("MySkin", "批量删除主题失败", e); null }
    }
    
    /**
     * 删除本地主题文件
     */
    private fun deleteLocalThemeFiles(themeIds: List<Int>) {
        try {
            val themeRootDir = java.io.File(requireContext().filesDir, "keyboard_themes")
            if (!themeRootDir.exists() || !themeRootDir.isDirectory) return
            
            themeIds.forEach { themeId ->
                val themeDir = java.io.File(themeRootDir, themeId.toString())
                if (themeDir.exists() && themeDir.isDirectory) {
                    themeDir.deleteRecursively()
                    Log.d("MySkin", "删除本地主题文件: ${themeDir.absolutePath}")
                }
            }
        } catch (e: Exception) {
            Log.e("MySkin", "删除本地主题文件失败", e)
        }
    }
}
