package com.example.petstoremobile.fragments.listfragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.petstoremobile.R;
import com.example.petstoremobile.adapters.ProductAdapter;
import com.example.petstoremobile.databinding.FragmentProductBinding;
import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.dtos.ProductDTO;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.ProductListViewModel;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class ProductFragment extends Fragment implements ProductAdapter.OnProductClickListener {

    private FragmentProductBinding binding;
    private List<ProductDTO> productList = new ArrayList<>();
    private ProductAdapter adapter;
    private ProductListViewModel viewModel;

    @Inject @Named("baseUrl") String baseUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentProductBinding.inflate(inflater, container, false);

        setupRecyclerView();
        setupSearch();
        setupCategoryFilter();
        setupSwipeRefresh();
        setupFilterToggle();
        observeViewModel();

        binding.fabAddProduct.setOnClickListener(v -> openProductDetails(-1));

        UIUtils.setupHamburgerMenu(binding.btnHamburgerProduct, this);

        return binding.getRoot();
    }

    private void observeViewModel() {
        viewModel.getProducts().observe(getViewLifecycleOwner(), list -> {
            productList.clear();
            productList.addAll(list);
            adapter.notifyDataSetChanged();
        });

        viewModel.getCategories().observe(getViewLifecycleOwner(), list -> {
            SpinnerUtils.populateWhiteSpinner(requireContext(), binding.spinnerCategory, list,
                    DropdownDTO::getLabel, "All Categories", -1L, DropdownDTO::getId);
        });

        viewModel.getIsLoading().observe(getViewLifecycleOwner(), loading -> {
            binding.swipeRefreshProduct.setRefreshing(loading);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        loadProductData(true);
        viewModel.loadCategories();
    }

    private void setupFilterToggle() {
        UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter,
                binding.etSearchProduct, binding.spinnerCategory);
    }

    private void setupSearch() {
        UIUtils.attachSearch(binding.etSearchProduct, () -> loadProductData(true));
    }

    private void setupCategoryFilter() {
        SpinnerUtils.setupFilterSpinner(binding.spinnerCategory, () -> loadProductData(true));
    }

    private void setupSwipeRefresh() {
        binding.swipeRefreshProduct.setOnRefreshListener(() -> loadProductData(true));
    }

    private void loadProductData(boolean reset) {
        String query = binding.etSearchProduct.getText().toString().trim();
        if (query.isEmpty()) query = null;

        Long categoryId = null;
        List<DropdownDTO> categories = viewModel.getCategories().getValue();
        if (binding.spinnerCategory.getSelectedItemPosition() > 0 && categories != null && !categories.isEmpty()) {
            categoryId = categories.get(binding.spinnerCategory.getSelectedItemPosition() - 1).getId();
        }

        viewModel.loadProducts(reset, query, categoryId);
    }

    private void setupRecyclerView() {
        adapter = new ProductAdapter(productList, this);
        adapter.setBaseUrl(baseUrl);
        binding.recyclerViewProducts.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewProducts.setAdapter(adapter);

        binding.recyclerViewProducts.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (dy <= 0) return;
                LinearLayoutManager lm = (LinearLayoutManager) binding.recyclerViewProducts.getLayoutManager();
                if (lm == null) return;
                int visible = lm.getChildCount();
                int total = lm.getItemCount();
                int firstVis = lm.findFirstVisibleItemPosition();
                Boolean isLoading = viewModel.getIsLoading().getValue();
                if ((isLoading == null || !isLoading) && !viewModel.isLastPage() && (visible + firstVis) >= total - 3) {
                    loadProductData(false);
                }
            }
        });
    }

    private void openProductDetails(int position) {
        Bundle args = new Bundle();
        if (position != -1) {
            ProductDTO product = productList.get(position);
            args.putLong("prodId", product.getProdId());
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_product_detail, args);
    }

    @Override
    public void onProductClick(int position) {
        openProductDetails(position);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
