package com.example.petstoremobile.fragments.listfragments;

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

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 com.example.petstoremobile.R;
import com.example.petstoremobile.adapters.ProductSupplierAdapter;
import com.example.petstoremobile.databinding.FragmentProductSupplierBinding;
import com.example.petstoremobile.dtos.ProductDTO;
import com.example.petstoremobile.dtos.ProductSupplierDTO;
import com.example.petstoremobile.dtos.SupplierDTO;
import com.example.petstoremobile.utils.BulkDeleteHandler;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.ProductSupplierListViewModel;

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

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class ProductSupplierFragment extends Fragment
        implements ProductSupplierAdapter.OnProductSupplierClickListener {

    private FragmentProductSupplierBinding binding;
    private List<ProductSupplierDTO> psList = new ArrayList<>();

    private ProductSupplierAdapter adapter;
    private ProductSupplierListViewModel viewModel;
    private BulkDeleteHandler bulkDeleteHandler;

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

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

        setupRecyclerView();
        setupSearch();
        setupProductFilter();
        setupSupplierFilter();
        setupSwipeRefresh();
        setupFilterToggle();
        setupBulkDelete();
        observeViewModel();

        binding.fabAddPS.setOnClickListener(v -> openDetail(-1));

        UIUtils.setupHamburgerMenu(binding.btnHamburgerPS, this);

        return binding.getRoot();
    }

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

        viewModel.getProducts().observe(getViewLifecycleOwner(), list -> {
            SpinnerUtils.populateWhiteSpinner(requireContext(), binding.spinnerProduct, list,
                    ProductDTO::getProdName, "All Products", -1L, ProductDTO::getProdId);
        });

        viewModel.getSuppliers().observe(getViewLifecycleOwner(), list -> {
            SpinnerUtils.populateWhiteSpinner(requireContext(), binding.spinnerSupplier, list,
                    SupplierDTO::getSupCompany, "All Suppliers", -1L, SupplierDTO::getSupId);
        });

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

    private void setupBulkDelete() {
        bulkDeleteHandler = new BulkDeleteHandler(
                this,
                binding.layoutBulkDelete,
                binding.tvSelectionCount,
                binding.btnBulkDelete,
                adapter,
                "relationship",
                viewModel::bulkDeleteProductSuppliers,
                () -> loadData(true)
        );
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(true);
        viewModel.loadFilterData();
    }

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

    private void setupFilterToggle() {
        UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter, binding.etSearchPS,
                binding.spinnerProduct, binding.spinnerSupplier);
    }

    private void setupRecyclerView() {
        adapter = new ProductSupplierAdapter(psList, this);
        binding.recyclerViewPS.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewPS.setAdapter(adapter);

        binding.recyclerViewPS.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (dy <= 0) return;
                LinearLayoutManager lm = (LinearLayoutManager) binding.recyclerViewPS.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) {
                    loadData(false);
                }
            }
        });
    }

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

    private void setupProductFilter() {
        SpinnerUtils.setupFilterSpinner(binding.spinnerProduct, () -> loadData(true));
    }

    private void setupSupplierFilter() {
        SpinnerUtils.setupFilterSpinner(binding.spinnerSupplier, () -> loadData(true));
    }

    private void setupSwipeRefresh() {
        binding.swipeRefreshPS.setOnRefreshListener(() -> loadData(true));
    }

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

        Long productId = null;
        List<ProductDTO> products = viewModel.getProducts().getValue();
        if (binding.spinnerProduct.getSelectedItemPosition() > 0 && products != null && !products.isEmpty()) {
            productId = products.get(binding.spinnerProduct.getSelectedItemPosition() - 1).getProdId();
        }

        Long supplierId = null;
        List<SupplierDTO> suppliers = viewModel.getSuppliers().getValue();
        if (binding.spinnerSupplier.getSelectedItemPosition() > 0 && suppliers != null && !suppliers.isEmpty()) {
            supplierId = suppliers.get(binding.spinnerSupplier.getSelectedItemPosition() - 1).getSupId();
        }

        viewModel.loadProductSuppliers(reset, query, productId, supplierId);
    }

    private void openDetail(int position) {
        Bundle args = new Bundle();
        if (position != -1) {
            ProductSupplierDTO ps = psList.get(position);
            args.putLong("productId", ps.getProductId());
            args.putLong("supplierId", ps.getSupplierId());
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_product_supplier_detail, args);
    }

    @Override
    public void onProductSupplierClick(int position) { openDetail(position); }

    @Override
    public void onSelectionChanged(int count) {
        if (bulkDeleteHandler != null) {
            bulkDeleteHandler.onSelectionChanged(count);
        }
    }
}
