package com.example.petstoremobile.fragments.listfragments;

import android.os.Bundle;
import android.view.*;
import androidx.annotation.NonNull;
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.CustomerAdapter;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.FragmentCustomerBinding;
import com.example.petstoremobile.dtos.CustomerDTO;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.CustomerListViewModel;
import dagger.hilt.android.AndroidEntryPoint;
import java.util.*;

import javax.inject.Inject;
import javax.inject.Named;

@AndroidEntryPoint
public class CustomerFragment extends Fragment implements CustomerAdapter.OnCustomerClickListener {

    private FragmentCustomerBinding binding;
    private CustomerListViewModel viewModel;
    private List<CustomerDTO> customerList = new ArrayList<>();
    private CustomerAdapter adapter;

    @Inject @Named("baseUrl") String baseUrl;
    @Inject TokenManager tokenManager;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentCustomerBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this).get(CustomerListViewModel.class);

        setupRecyclerView();
        setupSearch();
        setupStatusFilter();
        setupSwipeRefresh();
        observeViewModel();

        viewModel.loadCustomers(true);

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

        UIUtils.setupHamburgerMenu(binding.btnHamburgerCustomer, this);
        UIUtils.setupFilterToggle(binding.btnToggleFilterCustomer, binding.layoutFilterCustomer,
                binding.etSearchCustomer, binding.spinnerStatusCustomer);

        return binding.getRoot();
    }

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

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

    private void setupRecyclerView() {
        adapter = new CustomerAdapter(customerList, this);
        adapter.setBaseUrl(baseUrl);
        adapter.setToken(tokenManager.getToken());
        binding.recyclerViewCustomer.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewCustomer.setAdapter(adapter);

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

    private void setupStatusFilter() {
        String[] statuses = {"All Statuses", "Active", "Inactive"};
        SpinnerUtils.setupStringFilterSpinner(requireContext(), binding.spinnerStatusCustomer, statuses, this::applyFilters);
    }

    private void setupSearch() {
        UIUtils.attachSearch(binding.etSearchCustomer, this::applyFilters);
    }

    private void applyFilters() {
        String query = binding.etSearchCustomer.getText().toString().trim();
        String status = binding.spinnerStatusCustomer.getSelectedItem() != null ?
                binding.spinnerStatusCustomer.getSelectedItem().toString() : "All Statuses";
        viewModel.filter(query, status);
    }

    private void setupSwipeRefresh() {
        binding.swipeRefreshCustomer.setOnRefreshListener(() -> viewModel.loadCustomers(true));
    }

    private void openDetail(int position) {
        Bundle args = new Bundle();
        if (position != -1) {
            CustomerDTO c = customerList.get(position);
            args.putLong("customerId", c.getCustomerId() != null ? c.getCustomerId() : -1);
            args.putString("username", c.getUsername() != null ? c.getUsername() : "");
            args.putString("firstName", c.getFirstName() != null ? c.getFirstName() : "");
            args.putString("lastName", c.getLastName() != null ? c.getLastName() : "");
            args.putString("email", c.getEmail() != null ? c.getEmail() : "");
            args.putString("phone", c.getPhone() != null ? c.getPhone() : "");
            args.putBoolean("active", Boolean.TRUE.equals(c.getActive()));
            args.putInt("loyaltyPoints", c.getLoyaltyPoints() != null ? c.getLoyaltyPoints() : 0);
            args.putBoolean("isEditing", true);
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_customer_detail, args);
    }

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

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