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;

@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;

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

    @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();
    }

    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);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(true);
        if (!isStaff()) viewModel.loadStores();
    }

    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);
        }
    }

    private boolean isStaff() {
        return "STAFF".equalsIgnoreCase(tokenManager.getRole());
    }

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

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

    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);
                }
            }
        });
    }

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

    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);
    }

    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);
    }

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

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