package com.paperapp.lenscape.preview

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.paperapp.lenscape.R
import com.paperapp.lenscape.databinding.ActivityBrowseBinding
import com.paperapp.lenscape.tools.BrowseAdapter
import com.paperapp.lenscape.element.MainViewModel
import com.paperapp.lenscape.element.Element
import com.paperapp.lenscape.tools.SetLoveListener
import com.paperapp.lenscape.TopBarUtils

class BrowseActivity : AppCompatActivity(), SetLoveListener {
    lateinit var binding: ActivityBrowseBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter: BrowseAdapter
    private var resultList: List<Element> = emptyList()
    private var searchKey = ""
    private var isClick = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBrowseBinding.inflate(layoutInflater)
        setContentView(binding.root)
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window,true)
        init()
    }

    private fun init() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        adapter = BrowseAdapter()
        adapter.setListener(this)
        binding.list.adapter = adapter
        binding.list.layoutManager = GridLayoutManager(this, 2)
        binding.tvStart.setOnClickListener { startSearch() }
        binding.imageBack.setOnClickListener { finish() }
        binding.editText.requestFocus()
        binding.editText.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
                startSearch()
                return@setOnEditorActionListener true
            }
            false
        }
        binding.imageClear.setOnClickListener {
            binding.editText.setText("")
        }
        viewModel.searchList.observe(this) { list ->
            resultList = list
            binding.searchPb.visibility = View.GONE
            Log.d("SearchResult", "result list size${list.size}")
            if (resultList.isNotEmpty()) {
                showEmpty(false)
                adapter.setList(resultList)
                adapter.notifyDataSetChanged()
            } else if (isClick) {
                showEmpty(true)
            }
        }
        binding.editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                searchKey = s.toString().trim()
                if (searchKey.isNotEmpty()) {
                    binding.imageClear.visibility = View.VISIBLE
                } else {
                    binding.imageClear.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable) {
            }
        })

    }

    private fun startSearch() {
        closeKeyboard()
        isClick = true
        binding.searchPb.visibility = View.VISIBLE
        if (searchKey.isNotEmpty()) {
            Log.d("SearchStart", "searchKey is$searchKey")
            viewModel.getSearchList(searchKey)
        } else {

            binding.searchPb.visibility = View.GONE
            Toast.makeText(
                this,
                getString(R.string.please_enter),
                Toast.LENGTH_SHORT
            ).show()

        }
    }

    private fun showEmpty(showEmpty: Boolean) {
        if (showEmpty) {
            binding.emptyLayout.visibility = View.VISIBLE
            binding.list.visibility = View.GONE
        } else {
            binding.emptyLayout.visibility = View.GONE
            binding.list.visibility = View.VISIBLE
        }
    }

    private fun closeKeyboard() {
        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
        val currentFocus = currentFocus ?: binding.root
        inputMethodManager?.hideSoftInputFromWindow(currentFocus.windowToken, 0)
    }

    override fun inItemClick(paper: Element) {
        val intent = Intent(this, ImagePreviewActivity::class.java)
        intent.putExtra(ImagePreviewActivity.paperKey, paper)
        startActivity(intent)
    }
}

