package com.webtoonviewer.ui.adapter

import android.graphics.Bitmap
import android.text.format.Formatter.formatFileSize
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R
import com.webtoonviewer.ui.data.FileItem
import com.webtoonviewer.utils.CommonUtils.getEllipsizedText
import com.webtoonviewer.utils.CommonUtils.getShortNameFromEpisode
import java.io.File

class FileAdapter(
    private val fileList: MutableList<FileItem>,
    private val onItemClick: (FileItem) -> Unit
) : RecyclerView.Adapter<FileAdapter.ViewHolder>() {

    private var showCheckboxes: Boolean = false
    private val selectedFiles = mutableListOf<FileItem>()

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val fileNameTextView: TextView = itemView.findViewById(R.id.textViewFileNameItem)
        val infoTextView: TextView = itemView.findViewById(R.id.textViewFileInfoItem)
        val iconImageView: ImageView = itemView.findViewById(R.id.file_icon)
        val checkBox: CheckBox = itemView.findViewById(R.id.file_checkbox)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_file, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val file = fileList[position]
        val fileNameTextView: TextView = holder.fileNameTextView
        fileNameTextView.text = file.name

        holder.itemView.setOnClickListener {
            onItemClick(file)
        }
        holder.checkBox.visibility = if (showCheckboxes) View.VISIBLE else View.GONE
        holder.checkBox.isChecked = selectedFiles.contains(file)

        holder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                // 如果选中，加入选中的文件列表
                selectedFiles.add(file)
            } else {
                // 如果取消选中，移除选中的文件
                selectedFiles.remove(file)
            }
        }

        if (File(file.path).isDirectory) {
            // 如果是目录，显示目录图标和包含项目数量
            holder.iconImageView.setImageResource(R.drawable.folder_18) // 设置为目录图标
            val itemsCount = File(file.path).listFiles()?.size ?: 0
            holder.infoTextView.text = "$itemsCount items"
        } else {
            // 如果是文件，显示文件图标和文件大小
            holder.iconImageView.setImageResource(R.drawable.document_18) // 设置为文件图标
            val fileSize = formatFileSize(File(file.path).length())  // 格式化文件大小
            holder.infoTextView.text = fileSize
        }
    }

    override fun getItemCount(): Int {
        return fileList.size
    }

    private fun initFiles() {
        fileList.clear()
    }

    private fun sortFiles(fileItems: MutableList<FileItem>): MutableList<FileItem> {
        val sortedList: MutableList<FileItem> = fileItems
        if (sortedList[0].name.split(".").isNotEmpty())
        sortedList.sortBy {
            it.name.substringBefore('.').toIntOrNull() ?: Int.MAX_VALUE
        }
        return sortedList
    }

    fun updateFiles(fileItems: MutableList<FileItem>) {
        initFiles()
        val sortedFiles = sortFiles(fileItems)
        fileList.addAll(sortedFiles)
        notifyDataSetChanged()
    }

    private fun formatFileSize(size: Long): String {
        val kb = size / 1024.0
        val mb = kb / 1024.0
        return when {
            mb >= 1 -> String.format("%.2f MB", mb)
            kb >= 1 -> String.format("%.2f KB", kb)
            else -> "$size B"
        }
    }

    fun toggleCheckboxesVisibility() {
        showCheckboxes = !showCheckboxes
        notifyDataSetChanged()  // 刷新 RecyclerView
    }

    fun getSelectedFiles(): List<FileItem> {
        return selectedFiles
    }
}