package com.webtoonviewer.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R
import com.webtoonviewer.db.Book
import com.webtoonviewer.network.SmbClientHelper
import com.webtoonviewer.repository.BookRepository
import com.webtoonviewer.ui.adapter.EpisodeAdapter
import com.webtoonviewer.ui.component.DownloadViewModel
import com.webtoonviewer.utils.CommonUtils.getEpisodeNameFromEpisode
import com.webtoonviewer.utils.CommonUtils.getEllipsizedText
import com.webtoonviewer.utils.SharedPreferencesHelper
import com.webtoonviewer.utils.Webtoon18Plus.WEBTOON18PLUS
import com.webtoonviewer.utils.loadImgFromAssets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class EpisodesActivity : AppCompatActivity() {
    private val bookRepository: BookRepository = BookRepository(this)
    private val bookIdPreferences: SharedPreferencesHelper = SharedPreferencesHelper(this, "book_id")
    private val downloadingPreference: SharedPreferencesHelper = SharedPreferencesHelper(this, "downloading")

    private lateinit var recyclerView: RecyclerView
    private lateinit var episodeAdapter: EpisodeAdapter
    private lateinit var book: Book
    private lateinit var title: String
    private lateinit var currentEpisode: String
    private lateinit var currentEpisodeTextView: TextView

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

        recyclerView = findViewById(R.id.recyclerViewEpisodesPageEpisodeList)
        recyclerView.layoutManager = GridLayoutManager(this, 4)

        title = intent.getStringExtra("selectedTitle") ?: ""
        val thumbnail = intent.getStringExtra("thumbnail") ?: ""
        if (title != "") {
            val titleTextView: TextView = findViewById(R.id.textViewEpisodesPageTitle)
            titleTextView.text = title

            val titleImageView: ImageView = findViewById(R.id.imageViewEpisodesPageImg)
            val bitmap = loadImgFromAssets(this, thumbnail)
            if (bitmap != null) {
                titleImageView.setImageBitmap(bitmap)
            } else {
                titleImageView.setImageResource(R.drawable.ic_launcher_background)
            }

            val btnDownload: ImageButton = findViewById(R.id.btnEpisodesPageDownload)

            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    val id = bookIdPreferences.readData(title, "0").toInt()
                    book = bookRepository.getBookById(id)!!

                    val authorTextView: TextView = findViewById(R.id.textViewEpisodesPageAuthor)
                    authorTextView.text = book.author

                    currentEpisodeTextView = findViewById(R.id.textViewEpisodesPageCurrentEpisode)
                    currentEpisode = book.bookmarkChapter
                    setCurrentEpisodeTextView()

                    currentEpisodeTextView.setOnClickListener {
                        val intent = Intent(this@EpisodesActivity, ImagesActivity::class.java)
                        intent.putExtra("selectedTitle", book.title)
                        intent.putExtra("selectedChapter", currentEpisode)
                        intent.putExtra("thumbnail", book.img)
                        intent.putExtra("position", book.bookmarkPosition)
                        intent.putExtra("offset", book.bookmarkTopOffset)
                        startActivity(intent)
                    }

                    val btnDescription: ImageButton = findViewById(R.id.btnEpisodesPageDescription)
                    btnDescription.setOnClickListener {
                        val intent = Intent(this@EpisodesActivity, DescriptionActivity::class.java)
                        intent.putExtra("id", book.id)
                        intent.putExtra("description", book.description)
                        startActivity(intent)
                    }

                    val isDownloading = downloadingPreference.readData("key", "n")
                    if (book.isLocal == 0 && isDownloading == "n") {
                        btnDownload.visibility = View.VISIBLE
                    }
                }
                // 数据加载完毕，更新 UI
                withContext(Dispatchers.Main) {
                    episodeAdapter = EpisodeAdapter(book.chapters) { selectedChapter ->
                        val intent = Intent(this@EpisodesActivity, ImagesActivity::class.java)

                        intent.putExtra("selectedTitle", title)
                        intent.putExtra("selectedChapter", selectedChapter)
                        intent.putExtra("thumbnail", thumbnail)
                        startActivity(intent)
                    }
                    recyclerView.adapter = episodeAdapter
                }
            }

            btnDownload.setOnClickListener{
                btnDownload.visibility = View.GONE
                downloadingPreference.saveData("key", "y")
                val smbClientHelper = SmbClientHelper(this)
                GlobalScope.launch(Dispatchers.IO) {
                    var isConnect = false
                    try {
                        isConnect = smbClientHelper.connect()
                        if (isConnect) {
                            withContext(Dispatchers.Main) {
                                Toast.makeText(this@EpisodesActivity, "开始下载", Toast.LENGTH_SHORT).show()
                            }
                            smbClientHelper.downloadWebtoon(title)
                        }
                    } catch (e: Exception) {
                        Log.e("SMB", "Error accessing SMB share", e)
                    } finally {
                        if (isConnect) {
                            smbClientHelper.disconnect()
                            withContext(Dispatchers.Main) {
                                Toast.makeText(this@EpisodesActivity, "下载完毕", Toast.LENGTH_SHORT).show()
                            }
                        }
                        bookRepository.updateIsLocal(book.id, 1)
                        downloadingPreference.saveData("key", "n")
                    }
                }
            }
        }

        val btn18: ImageButton = findViewById(R.id.btnEpisodesPage18)
        if (WEBTOON18PLUS.contains("$title[18+]")) {
            btn18.visibility = View.VISIBLE
            btn18.setOnClickListener {
                val intent = Intent(this, EpisodesActivity::class.java)
                intent.putExtra("selectedTitle", "$title[18+]")
                intent.putExtra("thumbnail", thumbnail)
                startActivity(intent)
            }
        }

        val btnBack: ImageButton = findViewById(R.id.btnEpisodesPageHome)
        btnBack.setOnClickListener {
            returnToLastActivity()
        }

        onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                returnToLastActivity()
            }
        })
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            refreshData()
        }
    }

    private suspend fun refreshData() {
        val id = bookIdPreferences.readData(title, "0").toInt()
        book = bookRepository.getBookById(id)!!
        currentEpisode = book.bookmarkChapter
        setCurrentEpisodeTextView()

    }

    private fun setCurrentEpisodeTextView() {
        if (currentEpisode != "") {
            currentEpisodeTextView.post {
                currentEpisodeTextView.text = getEllipsizedText(
                    currentEpisodeTextView, "${"继续阅读： " + getEpisodeNameFromEpisode(currentEpisode)} >>"
                )
            }
        } else {
            currentEpisode = book.chapters[0]
            currentEpisodeTextView.post {
                currentEpisodeTextView.text = getEllipsizedText(
                    currentEpisodeTextView,
                    "开始阅读: ${getEpisodeNameFromEpisode(currentEpisode)} >>"
                )
            }
        }
    }

    private fun returnToLastActivity() {
        val resultIntent = Intent().apply {
            putExtra("bookmarkUpdated", book.title)
        }
        setResult(Activity.RESULT_OK, resultIntent)
        finish()
    }

}



