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.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petstoremobile.R;
import com.example.petstoremobile.adapters.CouponAdapter;
import com.example.petstoremobile.databinding.FragmentCouponBinding;
import com.example.petstoremobile.dtos.CouponDTO;
import com.example.petstoremobile.utils.Resource;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.CouponListViewModel;

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

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class CouponFragment extends Fragment implements CouponAdapter.OnCouponClickListener {
    private FragmentCouponBinding binding;
    private CouponListViewModel viewModel;
    private CouponAdapter adapter;
    private final List<CouponDTO> couponList = new ArrayList<>();

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

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

        applyFilters(true);

        binding.fabAddCoupon.setOnClickListener(v -> openDetail(-1));
        binding.btnBulkDeleteCoupons.setOnClickListener(v -> confirmBulkDelete());

        UIUtils.setupHamburgerMenu(binding.btnHamburgerCoupon, this);
        UIUtils.setupFilterToggle(binding.btnToggleFilterCoupon, binding.layoutFilterCoupon, binding.etSearchCoupon,
                binding.spinnerTypeCoupon, binding.spinnerStatusCoupon);

        return binding.getRoot();
    }

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

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

    private void setupRecyclerView() {
        adapter = new CouponAdapter(couponList, this);
        binding.recyclerViewCoupon.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewCoupon.setAdapter(adapter);

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

    private void setupStatusFilter() {
        String[] statuses = {"All Statuses", "Active", "Inactive"};
        SpinnerUtils.setupStringFilterSpinner(requireContext(), binding.spinnerStatusCoupon, statuses, () -> applyFilters(true));
    }

    private void setupTypeFilter() {
        String[] types = {"All Types", "FIXED", "PERCENT"};
        SpinnerUtils.setupStringFilterSpinner(requireContext(), binding.spinnerTypeCoupon, types, () -> applyFilters(true));
    }

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

    private void setupSwipeRefresh() {
        binding.swipeRefreshCoupon.setOnRefreshListener(() -> applyFilters(true));
    }

    private void applyFilters(boolean reset) {
        String statusStr = binding.spinnerStatusCoupon.getSelectedItem() != null ?
                binding.spinnerStatusCoupon.getSelectedItem().toString() : "All Statuses";
        Boolean active = null;
        if (statusStr.equals("Active")) active = true;
        else if (statusStr.equals("Inactive")) active = false;

        String typeStr = binding.spinnerTypeCoupon.getSelectedItem() != null ?
                binding.spinnerTypeCoupon.getSelectedItem().toString() : "All Types";
        String discountType = typeStr.equals("All Types") ? null : typeStr;

        viewModel.loadCoupons(reset, active, discountType, null);
    }

    private void openDetail(long id) {
        Bundle args = new Bundle();
        args.putLong("couponId", id);
        Navigation.findNavController(requireView()).navigate(R.id.couponDetailFragment, args);
    }

    @Override
    public void onCouponClick(CouponDTO coupon) {
        openDetail(coupon.getCouponId());
    }

    @Override
    public void onSelectionChanged(int count) {
        binding.btnBulkDeleteCoupons.setVisibility(count > 0 ? View.VISIBLE : View.GONE);
    }

    private void confirmBulkDelete() {
        new AlertDialog.Builder(requireContext())
                .setTitle("Confirm Bulk Delete")
                .setMessage("Are you sure you want to delete the selected coupons?")
                .setPositiveButton("Delete", (dialog, which) -> {
                    List<Long> ids = new ArrayList<>(adapter.getSelectedIds());
                    viewModel.bulkDeleteCoupons(ids).observe(getViewLifecycleOwner(), resource -> {
                        if (resource.status == Resource.Status.SUCCESS) {
                            adapter.setSelectionMode(false);
                            applyFilters(true);
                        } else if (resource.status == Resource.Status.ERROR) {
                            UIUtils.showToast(requireContext(), resource.message);
                        }
                    });
                })
                .setNegativeButton("Cancel", null)
                .show();
    }
}
