import 'package:flutter/material.dart';

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

import 'package:pweb/utils/text_field_styles.dart';

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


class WalletForm extends StatefulWidget {
  final void Function(WalletPaymentMethod) onChanged;
  final WalletPaymentMethod? initialData;
  final bool isEditable;

  const WalletForm({
    super.key,
    required this.onChanged,
    this.initialData,
    required this.isEditable,
  });

  @override
  State<WalletForm> createState() => _WalletFormState();
}

class _WalletFormState extends State<WalletForm> {
  late TextEditingController _walletIdController;

  @override
  void initState() {
    super.initState();
    _walletIdController = TextEditingController(text: widget.initialData?.walletId);
  }

  void _emit() {
    if (_walletIdController.text.isNotEmpty) {
      widget.onChanged(WalletPaymentMethod(walletId: _walletIdController.text));
    } else {
    }
  }

  @override
  void didUpdateWidget(covariant WalletForm oldWidget) {
    super.didUpdateWidget(oldWidget);
    final newData = widget.initialData;
    final oldData = oldWidget.initialData;

    if (newData == null && oldData != null) {
      _walletIdController.clear();
      return;
    }

    if (newData != null && newData != oldData) {
      if (newData.walletId != _walletIdController.text) {
        _walletIdController.text = newData.walletId;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;

    return TextFormField(
      readOnly: !widget.isEditable,
      controller: _walletIdController,
      decoration: getInputDecoration(context, l10n.walletId, widget.isEditable),
      style: getTextFieldStyle(context, widget.isEditable),
      onChanged: (_) => _emit(),
      validator: (val) => (val?.isEmpty ?? true) ? l10n.enterWalletId : null,
    );
  }
}
