package com.divya.hardinfo.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.divya.hardinfo.databinding.FragmentSearchBinding
import com.divya.hardinfo.viewmodel.HardwareViewModel

class SearchFragment : Fragment() {

    private var _binding: FragmentSearchBinding? = null
    private val binding get() = _binding!!
    private val viewModel: HardwareViewModel by viewModels()

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = HardwareAdapter { item ->
            val action = SearchFragmentDirections.actionSearchToDetail(item.id)
            findNavController().navigate(action)
        }

        // Simple adapter for history (String list)
        val historyAdapter = com.divya.hardinfo.ui.HistoryAdapter { query ->
            binding.searchView.setQuery(query, true)
        }

        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = adapter
        
        binding.historyRecyclerView.layoutManager = LinearLayoutManager(context)
        binding.historyRecyclerView.adapter = historyAdapter
        
        // Load initial history
        viewModel.getSearchHistory().observe(viewLifecycleOwner) { history ->
             historyAdapter.submitList(history)
             updateVisibility(binding.searchView.query.toString(), history.isNotEmpty())
        }
        
        binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                query?.let { viewModel.search(it) }
                binding.searchView.clearFocus()
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                 if (newText.isNullOrBlank()) {
                     updateVisibility("", true) // Show history if available
                 } else {
                     viewModel.search(newText)
                     updateVisibility(newText, false)
                 }
                return true
            }
        })
        
        viewModel.searchResults.observe(viewLifecycleOwner) { items ->
             adapter.submitList(items)
             updateVisibility(binding.searchView.query.toString(), false)
        }
    }
    
    private fun updateVisibility(query: String, showHistory: Boolean) {
        if (query.isBlank()) {
            binding.recyclerView.visibility = View.GONE
            binding.emptyView.visibility = View.GONE
            binding.historyRecyclerView.visibility = if (showHistory) View.VISIBLE else View.GONE
        } else {
            binding.historyRecyclerView.visibility = View.GONE
            // If we have results, results view will handle empty vs list
            // But we need to check adapter count? Actually observe logic handles data.
            // Just ensure recyclerView is visible if we have query
             if (binding.recyclerView.adapter?.itemCount == 0) {
                 binding.recyclerView.visibility = View.GONE
                 binding.emptyView.visibility = View.VISIBLE
             } else {
                 binding.recyclerView.visibility = View.VISIBLE
                 binding.emptyView.visibility = View.GONE
             }
        }
    }

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