package com.webtoonviewer.ui

import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R
import com.webtoonviewer.repository.BookRepository
import com.webtoonviewer.ui.adapter.TitleAdapter
import com.webtoonviewer.ui.data.TitleItem
import com.webtoonviewer.utils.SharedPreferencesHelper
import com.webtoonviewer.utils.Webtoon18Plus.WEBTOON18PLUS
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity(), TitleAdapter.OnItemClickListener {

    private val bookIdPreferences: SharedPreferencesHelper = SharedPreferencesHelper(this, "book_id")
    private val tagsVisibilityPreferences: SharedPreferencesHelper = SharedPreferencesHelper(this, "tags_visibility")
    private lateinit var bookRepository: BookRepository

    private lateinit var recyclerView: RecyclerView
    private lateinit var mainAdapter: TitleAdapter
    private lateinit var titleItems: MutableList<TitleItem>

//    private val manageExternalStoragePermissionLauncher =
//        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
//            if (android.os.Environment.isExternalStorageManager()) {
//                Toast.makeText(this, "外部存储权限已授予", Toast.LENGTH_SHORT).show()
//            } else {
//                Toast.makeText(this, "外部存储权限被拒绝", Toast.LENGTH_SHORT).show()
//            }
//        }

    private val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data: Intent? = result.data
                val title = data?.getStringExtra("bookmarkUpdated")
                title?.let {
                    // 在当前 Activity 的协程作用域中调用 refreshData
                    lifecycleScope.launch {
                        refreshData(it)
                    }
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textViewWV : TextView = findViewById(R.id.textViewMainPage)
        textViewWV.setOnClickListener {
            refreshActivity()
        }

        val settingsButton: ImageButton = findViewById(R.id.btnMainPage)
        settingsButton.setOnClickListener {
            val dialog = DialogMainSettingsFragment()
            dialog.show(supportFragmentManager, "DialogMainSettingsFragment")
        }

        bookRepository = BookRepository(this)

//        if (!externalStoragePermission.hasManageExternalStoragePermission()) {
//            externalStoragePermission.requestManageExternalStoragePermission(
//                manageExternalStoragePermissionLauncher
//            )
//        }

        recyclerView = findViewById(R.id.recyclerViewTitleList)
        recyclerView.layoutManager = GridLayoutManager(this, 3)

        titleItems = mutableListOf()

        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                val titles = bookRepository.getAllBookTitles()
                titleItems = generateTitleItems(titles)
            }
            // 数据加载完毕，更新 UI
            withContext(Dispatchers.Main) {
                mainAdapter = TitleAdapter(this@MainActivity, titleItems, this@MainActivity)
                recyclerView.adapter = mainAdapter
            }
        }

        lifecycleScope.launch {
            val bookmarkUpdated = intent.getStringExtra("bookmarkUpdated") ?: ""
            if (bookmarkUpdated != "") {
                refreshData(bookmarkUpdated)
            }
        }
    }

    private suspend fun generateTitleItems(titles: MutableList<String>): MutableList<TitleItem> {
        val titleItems: MutableList<TitleItem> = mutableListOf()
        withContext(Dispatchers.IO) {
            for (title in titles) {
                if (!WEBTOON18PLUS.contains(title)) {
                    val id = bookIdPreferences.readData(title, "0").toInt()
                    val book = bookRepository.getBookById(id)
                    val tag = book?.tag ?: ""
                    if (tagsVisibilityPreferences.getBoolean("showAll", false) ||
                        tagsVisibilityPreferences.getBoolean(tag, false)) {
                        val imageName = book?.img ?: ""
                        val chapter = if (book?.bookmarkChapter.isNullOrEmpty()) {
                            book?.chapters?.get(0).toString()
                        } else {
                            book?.bookmarkChapter ?: ""
                        }
                        val position = book?.bookmarkPosition ?: 0
                        val offset = book?.bookmarkTopOffset ?: 0
                        titleItems.add(TitleItem(imageName, title, tag, chapter, position, offset))
                    }
                }
            }
        }
        return titleItems
    }

    override fun clickToEpisodeList(titleItem: TitleItem) {
        val intent = Intent(this, EpisodesActivity::class.java)
        intent.putExtra("selectedTitle", titleItem.title)
        intent.putExtra("thumbnail", titleItem.thumbnail)
        startForResult.launch(intent)
    }

    override fun clickToSingleEpisode(titleItem: TitleItem) {
        val intent = Intent(this, ImagesActivity::class.java)
        intent.putExtra("selectedTitle", titleItem.title)
        intent.putExtra("selectedChapter", titleItem.chapter)
        intent.putExtra("thumbnail", titleItem.thumbnail)
        intent.putExtra("position", titleItem.position)
        intent.putExtra("offset", titleItem.offset)
        startForResult.launch(intent)
    }

    private suspend fun refreshData(title: String) {
        val titleItem = titleItems.find { it.title == title }
        val id = bookIdPreferences.readData(title, "0").toInt()
        val book = bookRepository.getBookById(id)

        titleItem?.chapter = if (book?.bookmarkChapter.isNullOrEmpty()) {
            book?.chapters?.get(0).toString()
        } else {
            book?.bookmarkChapter ?: ""
        }
        titleItem?.position = book?.bookmarkPosition ?: 0
        titleItem?.offset = book?.bookmarkTopOffset ?: 0
        if (titleItem != null) {
            mainAdapter.updateItem(titleItem)
        }
    }

    fun refreshActivity() {
        finish()
        startActivity(intent)
    }
}