import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

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

import 'package:pweb/providers/payment_methods.dart';
import 'package:pweb/pages/payment_methods/add/widget.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class PaymentConfigController {
  final BuildContext context;

  PaymentConfigController(this.context);

  void loadMethods() {
    context.read<PaymentMethodsProvider>().loadMethods();
  }

  Future<void> addMethod() async {
    final methodsProvider = context.read<PaymentMethodsProvider>();
    await showDialog<PaymentMethodData>(
      context: context,
      builder: (_) => const AddPaymentMethodDialog(),
    );
    methodsProvider.loadMethods();
  }

  Future<void> editMethod(PaymentMethod method) async {
    // TODO: implement edit functionality
  }

  Future<void> deleteMethod(PaymentMethod method) async {
    final methodsProvider = context.read<PaymentMethodsProvider>();
    final l10n = AppLocalizations.of(context)!;
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: Text(l10n.delete),
        content: Text(l10n.deletePaymentConfirmation),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(dialogContext, false),
            child: Text(l10n.cancel),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(dialogContext, true),
            child: Text(l10n.delete),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      methodsProvider.deleteMethod(method);
    }
  }

  void toggleEnabled(PaymentMethod method, bool value) {
    context.read<PaymentMethodsProvider>().toggleEnabled(method, value);
  }

  void makeMain(PaymentMethod method) {
    context.read<PaymentMethodsProvider>().makeMain(method);
  }

  void reorder(int oldIndex, int newIndex) {
    context.read<PaymentMethodsProvider>().reorderMethods(oldIndex, newIndex);
  }
}
