import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/payment/type.dart';
import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/provider/recipient/methods_cache.dart';
import 'package:pshared/provider/recipient/provider.dart';

import 'package:pweb/pages/address_book/form/body.dart';
import 'package:pweb/providers/address_book_recipient_form.dart';
import 'package:pweb/utils/payment/availability.dart';
import 'package:pweb/utils/payment/label.dart';

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


class AddressBookRecipientForm extends StatefulWidget {
  final Recipient? recipient;
  final ValueChanged<Recipient?>? onSaved;

  const AddressBookRecipientForm({super.key, this.recipient, this.onSaved});

  @override
  State<AddressBookRecipientForm> createState() => _AddressBookRecipientFormState();
}

class _AddressBookRecipientFormState extends State<AddressBookRecipientForm> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameCtrl;
  late TextEditingController _emailCtrl;

  static const List<PaymentType> _supportedTypes = visiblePaymentTypes;

  @override
  void initState() {
    super.initState();
    final r = widget.recipient;
    _nameCtrl = TextEditingController(text: r?.name ?? '');
    _emailCtrl = TextEditingController(text: r?.email ?? '');
  }

  Map<PaymentType, String> _methodNames(BuildContext context) => {
    for (final type in _supportedTypes) type: getPaymentTypeLabel(context, type),
  };

  Future<void> _save(AddressBookRecipientFormProvider formState) async {
    final l10n = AppLocalizations.of(context)!;
    if (!_formKey.currentState!.validate() || !formState.hasAnyMethod) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.recipientFormRule)),
      );
      return;
    }

    try {
      final saved = await formState.save(
        name: _nameCtrl.text,
        email: _emailCtrl.text,
        methodNames: _methodNames(context),
      );
      widget.onSaved?.call(saved);
    } catch (_) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(l10n.notificationError(l10n.noErrorInformation))),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider2<
      RecipientsProvider,
      RecipientMethodsCacheProvider,
      AddressBookRecipientFormProvider
    >(
      create: (_) => AddressBookRecipientFormProvider(
        recipient: widget.recipient,
        supportedTypes: _supportedTypes,
      ),
      update: (_, recipientsProvider, methodsCache, formProvider) =>
          formProvider!..updateProviders(
            recipientsProvider: recipientsProvider,
            methodsCache: methodsCache,
          ),
      child: AddressBookRecipientFormBody(
        formKey: _formKey,
        nameCtrl: _nameCtrl,
        emailCtrl: _emailCtrl,
        isEditing: widget.recipient != null,
        onSave: _save,
        onBack: () => widget.onSaved?.call(null),
      ),
    );
  }
}
