package com.design.wallpapergallery.view

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.ad.tradpluslibrary.TPAdManager.showTPAD
import com.design.wallpapergallery.R
import com.design.wallpapergallery.adapter.MoreAndSearchAdapter
import com.design.wallpapergallery.data.MainViewModel
import com.design.wallpapergallery.data.Photo
import com.design.wallpapergallery.databinding.ActivityFindByNameBinding
import com.design.wallpapergallery.listener.MainSecListener

class FindByNameActivity : AppCompatActivity(), MainSecListener {
    lateinit var binding: ActivityFindByNameBinding
    private lateinit var viewModel: MainViewModel
    private lateinit var adapter: MoreAndSearchAdapter
    private var resultList: List<Photo> = emptyList()
    private var searchKey = ""
    private var isClick = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFindByNameBinding.inflate(layoutInflater)
        setContentView(binding.root)
        init()
    }

    private fun init() {
        showTPAD(this) { null }
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        adapter = MoreAndSearchAdapter()
        adapter.setListener(this)
        binding.list.adapter = adapter
        binding.list.layoutManager = GridLayoutManager(this, 2)
        binding.tvStart.setOnClickListener {  showTPAD(this) {startSearch()} }
        binding.imageBack.setOnClickListener { finish() }
        binding.editText.requestFocus()
        binding.editText.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
                showTPAD(this) {
                    startSearch()
                }
                return@setOnEditorActionListener true
            }
            false
        }
        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.tvStart.visibility = View.VISIBLE
                } else {
                    binding.tvStart.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: Photo) {
        val intent = Intent(this, StartDownApplyActivity::class.java)
        intent.putExtra(StartDownApplyActivity.paperKey, paper)
        startActivity(intent)
    }
}

