package com.rugvedsarika.shoplist.ui.items

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rugvedsarika.shoplist.R
import com.rugvedsarika.shoplist.ShopListApp
import com.rugvedsarika.shoplist.data.local.entities.ShoppingItem
import com.rugvedsarika.shoplist.databinding.ActivityItemsBinding

class ItemsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityItemsBinding
    private lateinit var viewModel: ItemsViewModel
    private lateinit var adapter: ItemsAdapter
    private var listId: Int = -1
    private var listName: String = ""

    companion object {
        private const val EXTRA_LIST_ID = "extra_list_id"
        private const val EXTRA_LIST_NAME = "extra_list_name"

        fun start(context: Context, listId: Int, listName: String) {
            val intent = Intent(context, ItemsActivity::class.java).apply {
                putExtra(EXTRA_LIST_ID, listId)
                putExtra(EXTRA_LIST_NAME, listName)
            }
            context.startActivity(intent)
        }
    }

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

        listId = intent.getIntExtra(EXTRA_LIST_ID, -1)
        listName = intent.getStringExtra(EXTRA_LIST_NAME) ?: ""

        if (listId == -1) {
            finish()
            return
        }

        binding.toolbar.title = listName
        binding.toolbar.setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() }
        
        binding.toolbar.inflateMenu(R.menu.menu_items)
        binding.toolbar.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.action_share -> {
                    shareList()
                    true
                }
                R.id.action_search -> {
                    true
                }
                else -> false
            }
        }
        
        val searchItem = binding.toolbar.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
            }
        })

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

        // Setup RecyclerView
        // Setup RecyclerView
        adapter = ItemsAdapter(
            onItemChecked = { item, isChecked ->
                viewModel.updateItem(item.copy(isPurchased = isChecked))
            },
            onEditClicked = { item ->
                showItemDialog(item)
            },
            onDeleteClicked = { item ->
                viewModel.deleteItem(item)
            }
        )
        binding.rvItems.layoutManager = LinearLayoutManager(this)
        binding.rvItems.adapter = adapter
        
        setupSwipeToDelete()

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

        // Setup FAB
        binding.fabAddItem.setOnClickListener {
            showItemDialog()
        }
    }

    private fun setupSwipeToDelete() {
        val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val position = viewHolder.adapterPosition
                val item = adapter.currentList[position]
                viewModel.deleteItem(item)
                Toast.makeText(this@ItemsActivity, "Item deleted", Toast.LENGTH_SHORT).show()
            }
        }
        val itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
        itemTouchHelper.attachToRecyclerView(binding.rvItems)
    }

    private fun showItemDialog(shoppingItem: ShoppingItem? = null) {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_item, null)
        val etName = dialogView.findViewById<EditText>(R.id.et_item_name)
        val etQuantity = dialogView.findViewById<EditText>(R.id.et_quantity)
        val etCategory = dialogView.findViewById<EditText>(R.id.et_category)

        if (shoppingItem != null) {
            etName.setText(shoppingItem.name)
            etQuantity.setText(shoppingItem.quantity)
            etCategory.setText(shoppingItem.category)
        }

        val title = if (shoppingItem == null) getString(R.string.add_item) else getString(R.string.edit_shopping_item)
        val positiveButtonText = if (shoppingItem == null) getString(R.string.add) else getString(R.string.save)

        MaterialAlertDialogBuilder(this)
            .setTitle(title)
            .setView(dialogView)
            .setPositiveButton(positiveButtonText) { _, _ ->
                val name = etName.text.toString().trim()
                val quantity = etQuantity.text.toString().trim()
                val category = etCategory.text.toString().trim()

                if (name.isNotEmpty()) {
                    if (shoppingItem == null) {
                        val newItem = ShoppingItem(
                            listId = listId,
                            name = name,
                            quantity = quantity,
                            category = category
                        )
                        viewModel.insertItem(newItem)
                    } else {
                        val updatedItem = shoppingItem.copy(
                            name = name,
                            quantity = quantity,
                            category = category
                        )
                        viewModel.updateItem(updatedItem)
                    }
                } else {
                    Toast.makeText(this, getString(R.string.enter_item_name), Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton(getString(R.string.cancel), null)
            .show()
    }
    private fun shareList() {
        val items = adapter.currentList
        if (items.isEmpty()) {
            Toast.makeText(this, "List is empty", Toast.LENGTH_SHORT).show()
            return
        }

        val sb = StringBuilder()
        sb.append("Shopping List: $listName\n\n")
        
        items.forEach { item ->
            val status = if (item.isPurchased) "[x]" else "[ ]"
            sb.append("$status ${item.name} (${item.quantity})")
            if (item.category.isNotEmpty()) {
                sb.append(" - ${item.category}")
            }
            sb.append("\n")
        }

        val sendIntent: Intent = Intent().apply {
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_TEXT, sb.toString())
            type = "text/plain"
        }

        val shareIntent = Intent.createChooser(sendIntent, "Share List")
        startActivity(shareIntent)
    }
}
