package com.aletheia.app.ui.reader

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.aletheia.app.AletheiaApplication
import com.aletheia.app.R
import com.aletheia.app.databinding.FragmentReaderHubBinding
import com.aletheia.app.model.Book
import com.aletheia.app.ui.main.MainActivity
import com.aletheia.app.util.setBookCover
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ReaderHubFragment : Fragment() {
    private var _binding: FragmentReaderHubBinding? = null
    private val binding get() = _binding!!
    private val app by lazy { requireActivity().application as AletheiaApplication }
    private var currentBook: Book? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View {
        _binding = FragmentReaderHubBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, state: Bundle?) {
        super.onViewCreated(view, state)
        binding.continueReadingButton.setOnClickListener { currentBook?.let(::openBook) }
        binding.currentBookCard.setOnClickListener { currentBook?.let(::openBook) }
        binding.findBookButton.setOnClickListener {
            (activity as? MainActivity)?.selectTab(R.id.nav_search)
        }
    }

    override fun onResume() {
        super.onResume()
        loadState()
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }

    private fun loadState() {
        viewLifecycleOwner.lifecycleScope.launch {
            val books = withContext(Dispatchers.IO) { app.bookRepository.getAllBooks() }
            if (_binding == null) return@launch
            currentBook = books.filter { it.readingProgress > 0.0 }.maxByOrNull { it.lastRead }
            val book = currentBook
            binding.readerEmptyState.visibility = if (book == null) View.VISIBLE else View.GONE
            binding.currentBookCard.visibility = if (book == null) View.GONE else View.VISIBLE
            binding.downloadedCount.text = getString(R.string.reader_hub_downloaded_count, books.size)
            if (book != null) {
                binding.currentBookCover.setBookCover(book.coverImage, R.drawable.default_cover)
                binding.currentBookTitle.text = book.title
                binding.currentBookAuthor.text = book.author
                val percent = (book.readingProgress * 100).toInt().coerceIn(0, 100)
                binding.currentBookProgress.progress = percent
                binding.currentBookProgressText.text = getString(R.string.reader_progress_percent, percent)
            }
        }
    }

    private fun openBook(book: Book) {
        startActivity(Intent(requireContext(), ReaderActivity::class.java).putExtra(ReaderActivity.EXTRA_BOOK_ID, book.id))
    }

    companion object {
        fun newInstance() = ReaderHubFragment()
    }
}
