import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pweb/controllers/organization/address_book_recipient_form.dart';
import 'package:pweb/controllers/organization/address_book_recipient_form_selection.dart';
import 'package:pweb/pages/address_book/form/view.dart';
import 'package:pweb/providers/address_book_recipient_form.dart';
import 'package:pweb/utils/payment/availability.dart';


class AddressBookRecipientFormBody extends StatelessWidget {
  final GlobalKey<FormState> formKey;
  final TextEditingController nameCtrl;
  final TextEditingController emailCtrl;
  final bool isEditing;
  final Future<void> Function(AddressBookRecipientFormProvider) onSave;
  final VoidCallback onBack;

  const AddressBookRecipientFormBody({
    required this.formKey,
    required this.nameCtrl,
    required this.emailCtrl,
    required this.isEditing,
    required this.onSave,
    required this.onBack,
  });

  @override
  Widget build(BuildContext context) {
    final formState = Provider.of<AddressBookRecipientFormProvider>(context, listen: false);
    final controller = Provider.of<AddressBookRecipientFormController>(context);
    final selection =
        Provider.of<AddressBookRecipientFormSelectionController>(context);

    if (controller.supportedTypes.isEmpty) {
      return const SizedBox.shrink();
    }

    final selectedType = selection.selectedType ?? controller.supportedTypes.first;
    return FormView(
      formKey: formKey,
      nameCtrl: nameCtrl,
      emailCtrl: emailCtrl,
      types: controller.supportedTypes,
      selectedType: selectedType,
      selectedIndex: selection.selectedIndex,
      methods: controller.methods,
      onMethodSelected: selection.select,
      onMethodAdd: (type) {
        final newIndex = controller.addMethod(type);
        selection.selectAfterAdd(type, newIndex);
      },
      disabledTypes: disabledPaymentTypes,
      onMethodRemove: (index) {
        final type = selection.selectedType ?? controller.supportedTypes.first;
        controller.removeMethod(type, index);
      },
      onMethodChanged: (index, data) {
        final type = selection.selectedType ?? controller.supportedTypes.first;
        controller.updateMethod(type, index, data);
      },
      onSave: () => onSave(formState),
      isEditing: isEditing,
      onBack: onBack,
    );
  }
}
