package com.example.petstoremobile.fragments.listfragments;

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

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.InventoryAdapter;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.FragmentInventoryBinding;
import com.example.petstoremobile.dtos.InventoryDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.utils.BulkDeleteHandler;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.InventoryListViewModel;
import com.example.petstoremobile.utils.SpinnerUtils;

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

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class InventoryFragment extends Fragment implements InventoryAdapter.OnInventoryClickListener {

    private FragmentInventoryBinding binding;
    private final List<InventoryDTO> inventoryList = new ArrayList<>();
    private InventoryAdapter adapter;
    private InventoryListViewModel viewModel;
    private BulkDeleteHandler bulkDeleteHandler;

    @Inject TokenManager tokenManager;

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

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

        setupRecyclerView();
        setupSearch();
        setupStoreFilter();
        setupSwipeRefresh();
        setupFilterToggle();
        setupBulkDelete();
        observeViewModel();
        
        loadInventory(true);

        binding.fabAddInventory.setOnClickListener(v -> openDetail(null));

        UIUtils.setupHamburgerMenu(binding.btnHamburger, this);

        return binding.getRoot();
    }

    private void observeViewModel() {
        viewModel.getInventory().observe(getViewLifecycleOwner(), list -> {
            inventoryList.clear();
            inventoryList.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.swipeRefreshInventory.setRefreshing(loading);
        });
    }

    private void setupBulkDelete() {
        bulkDeleteHandler = new BulkDeleteHandler(
                this,
                binding.layoutBulkDelete,
                binding.tvSelectionCount,
                binding.btnBulkDelete,
                adapter,
                "inventory item",
                viewModel::bulkDeleteInventory,
                () -> loadInventory(true)
        );
    }

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

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

    private void setupFilterToggle() {
        if (isStaff()) {
            UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter, binding.etSearchInventory);
            binding.spinnerStore.setVisibility(View.GONE);
        } else {
            UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter, binding.etSearchInventory, binding.spinnerStore);
        }
    }

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

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

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

    private void setupRecyclerView() {
        adapter = new InventoryAdapter(inventoryList, this);
        binding.recyclerViewInventory.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewInventory.setAdapter(adapter);

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

    private void setupSwipeRefresh() {
        binding.swipeRefreshInventory.setOnRefreshListener(() -> loadInventory(true));
    }

    private void loadInventory(boolean reset) {
        String query = binding.etSearchInventory != null ? binding.etSearchInventory.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.loadInventory(reset, query, storeId);
    }

    private void openDetail(InventoryDTO inv) {
        Bundle args = new Bundle();
        if (inv != null) {
            args.putLong("inventoryId", inv.getInventoryId());
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_inventory_detail, args);
    }

    @Override
    public void onInventoryClick(int position) {
        if (position >= 0 && position < inventoryList.size()) {
            openDetail(inventoryList.get(position));
        }
    }

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