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.PurchaseOrderAdapter;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.FragmentPurchaseOrderBinding;
import com.example.petstoremobile.dtos.PurchaseOrderDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.PurchaseOrderListViewModel;

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

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * Fragment for displaying and managing a list of purchase orders.
 */
@AndroidEntryPoint
public class PurchaseOrderFragment extends Fragment
        implements PurchaseOrderAdapter.OnPurchaseOrderClickListener {

    private FragmentPurchaseOrderBinding binding;
    private List<PurchaseOrderDTO> poList = new ArrayList<>();
    private PurchaseOrderAdapter adapter;
    private PurchaseOrderListViewModel viewModel;

    @Inject TokenManager tokenManager;

    /**
     * Initializes the ViewModel.
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(PurchaseOrderListViewModel.class);
    }

    /**
     * Inflates the layout and sets up UI components, filters, and observers.
     */
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentPurchaseOrderBinding.inflate(inflater, container, false);

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

        UIUtils.setupHamburgerMenu(binding.btnHamburgerPO, this);

        return binding.getRoot();
    }

    /**
     * Observes the ViewModel for purchase order list, stores, and loading status.
     */
    private void observeViewModel() {
        viewModel.getPurchaseOrders().observe(getViewLifecycleOwner(), list -> {
            poList.clear();
            poList.addAll(list);
            adapter.notifyDataSetChanged();
        });

        viewModel.getStores().observe(getViewLifecycleOwner(), list -> {
            SpinnerUtils.populateWhiteSpinner(requireContext(), binding.spinnerStore, list,
                    StoreDTO::getStoreName, "All Stores", -1L, StoreDTO::getStoreId);
        });

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

    /**
     * Reloads data and stores if necessary when the fragment resumes.
     */
    @Override
    public void onResume() {
        super.onResume();
        loadData(true);
        if (!isStaff()) viewModel.loadStores();
    }

    /**
     * Sets up the filter visibility toggle
     */
    private void setupFilterToggle() {
        if (isStaff()) {
            UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter, binding.etSearchPO);
            binding.spinnerStore.setVisibility(View.GONE);
        } else {
            UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter, binding.etSearchPO, binding.spinnerStore);
        }
    }

    /**
     * Checks if the currently logged-in user has the STAFF role.
     */
    private boolean isStaff() {
        return "STAFF".equalsIgnoreCase(tokenManager.getRole());
    }

    /**
     * Sets up the search input listener.
     */
    private void setupSearch() {
        UIUtils.attachSearch(binding.etSearchPO, () -> loadData(true));
    }

    /**
     * Configures the store filter spinner.
     */
    private void setupStoreFilter() {
        SpinnerUtils.setupFilterSpinner(binding.spinnerStore, () -> loadData(true));
    }

    /**
     * Configures the RecyclerView and its scroll listener for pagination.
     */
    private void setupRecyclerView() {
        adapter = new PurchaseOrderAdapter(poList, this);
        binding.recyclerViewPO.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewPO.setAdapter(adapter);

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

    /**
     * Configures the swipe-to-refresh layout.
     */
    private void setupSwipeRefresh() {
        binding.swipeRefreshPO.setOnRefreshListener(() -> loadData(true));
    }

    /**
     * Loads purchase order data based on current search query and store filter.
     */
    private void loadData(boolean reset) {
        String query = binding.etSearchPO != null ? binding.etSearchPO.getText().toString().trim() : "";
        if (query.isEmpty()) query = null;

        Long storeId;
        if (isStaff()) {
            storeId = tokenManager.getPrimaryStoreId();
        } else {
            storeId = null;
            List<StoreDTO> stores = viewModel.getStores().getValue();
            if (binding.spinnerStore.getSelectedItemPosition() > 0 && stores != null && !stores.isEmpty()) {
                storeId = stores.get(binding.spinnerStore.getSelectedItemPosition() - 1).getStoreId();
            }
        }

        viewModel.loadPurchaseOrders(reset, query, storeId);
    }

    /**
     * Navigates to the purchase order detail screen.
     */
    private void openDetail(int position) {
        Bundle args = new Bundle();
        PurchaseOrderDTO po = poList.get(position);
        args.putLong("purchaseOrderId", po.getPurchaseOrderId());
        NavHostFragment.findNavController(this).navigate(R.id.nav_purchase_order_detail, args);
    }

    /**
     * Handles purchase order item clicks by opening details.
     */
    @Override
    public void onPurchaseOrderClick(int position) {
        openDetail(position);
    }

    /**
     * Cleans up the binding reference.
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
