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.SupplierAdapter;
import com.example.petstoremobile.databinding.FragmentSupplierBinding;
import com.example.petstoremobile.dtos.SupplierDTO;
import com.example.petstoremobile.utils.BulkDeleteHandler;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.SupplierListViewModel;

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

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class SupplierFragment extends Fragment implements SupplierAdapter.OnSupplierClickListener {

    private FragmentSupplierBinding binding;
    private List<SupplierDTO> supplierList = new ArrayList<>();
    private SupplierAdapter adapter;
    private SupplierListViewModel viewModel;
    private BulkDeleteHandler bulkDeleteHandler;

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

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

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

        loadSupplierData(true);

        binding.fabAddSupplier.setOnClickListener(v -> openSupplierDetails(-1));

        UIUtils.setupHamburgerMenu(binding.btnHamburger, this);

        return binding.getRoot();
    }

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

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

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

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

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

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

    private void setupSwipeRefresh() {
        binding.swipeRefreshSupplier.setOnRefreshListener(() -> loadSupplierData(true));
    }

    private void openSupplierDetails(int position) {
        Bundle args = new Bundle();
        if (position != -1) {
            SupplierDTO supplier = supplierList.get(position);
            args.putLong("supId", supplier.getSupId());
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_supplier_detail, args);
    }

    @Override
    public void onSupplierClick(int position) {
        openSupplierDetails(position);
    }

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

    private void loadSupplierData(boolean reset) {
        String query = binding.etSearchSupplier != null ? binding.etSearchSupplier.getText().toString().trim() : "";
        if (query.isEmpty()) query = null;
        viewModel.loadSuppliers(reset, query);
    }

    private void setupRecyclerView() {
        adapter = new SupplierAdapter(supplierList, this);
        binding.recyclerViewSuppliers.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewSuppliers.setAdapter(adapter);

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