package com.example.orderly.ui.catalog

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.CompositePageTransformer
import androidx.viewpager2.widget.MarginPageTransformer
import androidx.viewpager2.widget.ViewPager2
import com.example.orderly.ui.OrderLyApplication
import com.example.orderly.R
import com.example.orderly.data.entity.Product
import com.example.orderly.databinding.FragmentCatalogBinding
import com.example.orderly.ui.OrderLyViewModel
import com.example.orderly.ui.OrderLyViewModelFactory
import kotlin.math.abs

class CatalogFragment : Fragment() {
    private var _binding: FragmentCatalogBinding? = null
    private val binding get() = _binding!!
    private val viewModel: OrderLyViewModel by viewModels {
        OrderLyViewModelFactory(
            (requireActivity().application as OrderLyApplication).repository
        )
    }
    private val sliderHandler = Handler(Looper.getMainLooper())
    private val sliderRunnable = Runnable {
        if (_binding != null) {
            val currentItem = binding.vpFeatured.currentItem
            val totalItems = binding.vpFeatured.adapter?.itemCount ?: 0
            if (totalItems > 0) {
                binding.vpFeatured.currentItem = (currentItem + 1) % totalItems
            }
        }
    }

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

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

        setupProductRecyclerView()
        setupSearchView()
        setupSlider()
        observeData()

        binding.cvProfile.setOnClickListener {
            findNavController().navigate(CatalogFragmentDirections.actionNavHomeToProfileFragment())
        }

        binding.fabLocation.setOnClickListener {
            findNavController().navigate(R.id.action_nav_home_to_mapFragment)
        }
    }

    private fun setupProductRecyclerView() {
        val productAdapter = ProductAdapter(
            onDeleteClick = { product ->
                showDeleteDialog(product)
            },
            onItemClick = { product ->
                val action = CatalogFragmentDirections.actionNavHomeToDetailFragment(product.id)
                findNavController().navigate(action)
            }
        )

        binding.rvProducts.layoutManager = GridLayoutManager(requireContext(), 2)
        binding.rvProducts.adapter = productAdapter
    }

    private fun setupSlider() {
        val bestSellerMenus = listOf(
            Product(
                id = -1,
                name = "Premium Burger Joy",
                description = "Double beef with melted cheese",
                price = 45000.0,
                imageUrl = "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?w=800",
                category = "Makanan"
            ),
            Product(
                id = -2,
                name = "Caramel Macchiato",
                description = "Perfect blend of coffee and caramel",
                price = 35000.0,
                imageUrl = "https://images.unsplash.com/photo-1541167760496-1628856ab752?w=800",
                category = "Minuman"
            ),
            Product(
                id = -3,
                name = "Spicy Ramen Noodle",
                description = "Hot and spicy authentic ramen",
                price = 50000.0,
                imageUrl = "https://images.unsplash.com/photo-1569718212165-3a8278d5f624?w=800",
                category = "Makanan"
            )
        )

        val featuredAdapter = FeaturedAdapter(bestSellerMenus)
        binding.vpFeatured.adapter = featuredAdapter

        binding.vpFeatured.apply {
            clipToPadding = false
            clipChildren = false
            offscreenPageLimit = 3
            getChildAt(0).overScrollMode = RecyclerView.OVER_SCROLL_NEVER

            val compositePageTransformer = CompositePageTransformer()
            compositePageTransformer.addTransformer(MarginPageTransformer(0))
            compositePageTransformer.addTransformer { page, position ->
                val r = 1 - abs(position)
                page.scaleY = 0.90f + r * 0.10f
            }
            setPageTransformer(compositePageTransformer)

            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    sliderHandler.removeCallbacks(sliderRunnable)
                    sliderHandler.postDelayed(sliderRunnable, 4000)
                }
            })
        }
    }

    private fun setupSearchView() {
        binding.etSearch.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) {
                viewModel.setSearchQuery(s.toString())
            }
            override fun afterTextChanged(s: Editable?) {}
        })
    }

    private fun observeData() {
        viewModel.filteredProducts.observe(viewLifecycleOwner) { products ->
            (binding.rvProducts.adapter as? ProductAdapter)?.submitList(products)
        }
    }

    private fun showDeleteDialog(product: Product) {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Produk")
            .setMessage("Yakin mau hapus ${product.name}?")
            .setPositiveButton("Hapus") { dialog, _ ->
                viewModel.deleteProduct(product)
                dialog.dismiss()
            }
            .setNegativeButton("Batal") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    override fun onResume() {
        super.onResume()
        sliderHandler.postDelayed(sliderRunnable, 4000)
    }

    override fun onPause() {
        super.onPause()
        sliderHandler.removeCallbacks(sliderRunnable)
    }

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