import 'package:flutter/material.dart';

import 'package:pshared/models/payment/methods/type.dart';

import 'package:pweb/services/payments/payment_methods.dart';


class PaymentMethodsProvider extends ChangeNotifier {
  final PaymentMethodsService service;

  List<PaymentMethod> _methods = [];
  PaymentMethod? _selectedMethod;
  bool _isLoading = false;
  String? _error;

  PaymentMethodsProvider({required this.service});

  List<PaymentMethod> get methods => _methods;
  PaymentMethod? get selectedMethod => _selectedMethod;
  bool get isLoading => _isLoading;
  String? get error => _error;

  Future<void> loadMethods() async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      _methods = await service.fetchMethods();
      _selectedMethod = _methods.firstWhere((m) => m.isMain, orElse: () => _methods.first);
    } catch (e) {
      _error = e.toString();
    }

    _isLoading = false;
    notifyListeners();
  }

  void selectMethod(PaymentMethod method) {
    _selectedMethod = method;
    notifyListeners();
  }

  void deleteMethod(PaymentMethod method) {
    _methods.remove(method);
    notifyListeners();
  }

  void reorderMethods(int oldIndex, int newIndex) {
    if (newIndex > oldIndex) newIndex--;
    final item = _methods.removeAt(oldIndex);
    _methods.insert(newIndex, item);
    notifyListeners();
  }

  void toggleEnabled(PaymentMethod method, bool value) {
    method.isEnabled = value;
    notifyListeners();
  }

  void makeMain(PaymentMethod method) {
    for (final m in _methods) m.isMain = false;
    method.isMain = true;
    selectMethod(method);
  }
}
