package com.rugvedsarika.shoplist.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rugvedsarika.shoplist.R
import com.rugvedsarika.shoplist.ShopListApp
import com.rugvedsarika.shoplist.data.local.entities.ShoppingList
import com.rugvedsarika.shoplist.databinding.ActivityMainBinding
import com.rugvedsarika.shoplist.ui.items.ItemsActivity

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: HomeViewModel
    private lateinit var adapter: ShoppingListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Setup Toolbar
        setSupportActionBar(binding.toolbar)

        // Setup ViewModel
        val repository = (application as ShopListApp).repository
        val factory = HomeViewModelFactory(repository)
        viewModel = ViewModelProvider(this, factory)[HomeViewModel::class.java]

        // Setup RecyclerView
        adapter = ShoppingListAdapter(
            onItemClicked = { shoppingList ->
                ItemsActivity.start(this, shoppingList.id, shoppingList.name)
            },
            onEditClicked = { shoppingList ->
                showListDialog(shoppingList)
            },
            onDeleteClicked = { shoppingList ->
                showDeleteConfirmationDialog(shoppingList)
            }
        )
        binding.rvShoppingLists.layoutManager = LinearLayoutManager(this)
        binding.rvShoppingLists.adapter = adapter

        // Observe Data
        viewModel.allShoppingLists.observe(this) { lists ->
            adapter.submitList(lists)
            binding.tvEmptyState.visibility = if (lists.isEmpty()) View.VISIBLE else View.GONE
        }

        // Setup FAB
        binding.fabAddList.setOnClickListener {
            showListDialog()
        }
    }

    override fun onCreateOptionsMenu(menu: android.view.Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        
        val searchItem = menu?.findItem(R.id.action_search)
        val searchView = searchItem?.actionView as? androidx.appcompat.widget.SearchView
        
        searchView?.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                viewModel.search(newText ?: "")
                return true
            }
        })
        
        return true
    }

    override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_settings -> {
                startActivity(android.content.Intent(this, com.rugvedsarika.shoplist.ui.settings.SettingsActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showListDialog(shoppingList: ShoppingList? = null) {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_list, null)
        val etListName = dialogView.findViewById<EditText>(R.id.et_list_name)

        if (shoppingList != null) {
            etListName.setText(shoppingList.name)
        }

        val title = if (shoppingList == null) getString(R.string.new_shopping_list) else getString(R.string.edit_shopping_list)
        val positiveButtonText = if (shoppingList == null) getString(R.string.create) else getString(R.string.save)

        MaterialAlertDialogBuilder(this)
            .setTitle(title)
            .setView(dialogView)
            .setPositiveButton(positiveButtonText) { _, _ ->
                val name = etListName.text.toString().trim()
                if (name.isNotEmpty()) {
                    if (shoppingList == null) {
                        val newList = ShoppingList(name = name)
                        viewModel.insert(newList)
                    } else {
                        val updatedList = shoppingList.copy(name = name)
                        viewModel.update(updatedList)
                    }
                } else {
                    Toast.makeText(this, getString(R.string.enter_list_name), Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton(getString(R.string.cancel), null)
            .show()
    }

    private fun showDeleteConfirmationDialog(shoppingList: ShoppingList) {
        MaterialAlertDialogBuilder(this)
            .setTitle(getString(R.string.delete_list))
            .setMessage("Are you sure you want to delete '${shoppingList.name}'?")
            .setPositiveButton("Delete") { _, _ ->
                viewModel.delete(shoppingList)
            }
            .setNegativeButton(getString(R.string.cancel), null)
            .show()
    }
}
