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.ServiceAdapter;
import com.example.petstoremobile.databinding.FragmentServiceBinding;
import com.example.petstoremobile.dtos.ServiceDTO;
import com.example.petstoremobile.utils.BulkDeleteHandler;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.ServiceListViewModel;

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

import dagger.hilt.android.AndroidEntryPoint;

/**
 * Fragment class for displaying a list of services in a RecyclerView.
 */
@AndroidEntryPoint
public class ServiceFragment extends Fragment implements ServiceAdapter.OnServiceClickListener {

    private FragmentServiceBinding binding;
    private final List<ServiceDTO> serviceList = new ArrayList<>();
    private ServiceAdapter adapter;
    private ServiceListViewModel viewModel;
    private BulkDeleteHandler bulkDeleteHandler;

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

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

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

        loadServices(true);

        UIUtils.setupHamburgerMenu(binding.btnHamburger, this);

        binding.fabAddService.setOnClickListener(v ->
                NavHostFragment.findNavController(this).navigate(R.id.nav_service_detail));

        return binding.getRoot();
    }

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

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

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

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

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

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

    private void setupRecyclerView() {
        adapter = new ServiceAdapter(serviceList, this);
        binding.recyclerViewServices.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewServices.setAdapter(adapter);

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

    private void setupSwipeRefresh() {
        binding.swipeRefreshService.setOnRefreshListener(() -> loadServices(true));
    }

    private void loadServices(boolean reset) {
        String query = binding.etSearchService.getText().toString().trim();
        if (query.isEmpty()) query = null;
        viewModel.loadServices(reset, query);
    }

    private void openDetail(ServiceDTO service) {
        Bundle args = new Bundle();
        if (service != null) {
            args.putLong("serviceId", service.getServiceId());
        }
        NavHostFragment.findNavController(this).navigate(R.id.nav_service_detail, args);
    }

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

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