import 'package:flutter/material.dart';

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

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

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


class IbanForm extends StatefulWidget {
  final void Function(IbanPaymentMethod) onChanged;
  final IbanPaymentMethod? initialData;
  final bool isEditable;

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

  @override
  State<IbanForm> createState() => _IbanFormState();
}

class _IbanFormState extends State<IbanForm> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _ibanController;
  late TextEditingController _accountHolderController;
  late TextEditingController _bicController;
  late TextEditingController _bankNameController;

  @override
  void initState() {
    super.initState();
    _ibanController = TextEditingController(text: widget.initialData?.iban ?? '');
    _accountHolderController = TextEditingController(text: widget.initialData?.accountHolder ?? '');
    _bicController = TextEditingController(text: widget.initialData?.bic ?? '');
    _bankNameController = TextEditingController(text: widget.initialData?.bankName ?? '');

    WidgetsBinding.instance.addPostFrameCallback((_) => _emitIfValid());
  }

  void _emitIfValid() {
    if (_formKey.currentState?.validate() ?? false) {
      widget.onChanged(
        IbanPaymentMethod(
          iban: _ibanController.text,
          accountHolder: _accountHolderController.text,
          bic: _bicController.text,
          bankName: _bankNameController.text,
        ),
      );
    }
  }

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

    if (newData == null && oldData != null) {
      _ibanController.clear();
      _accountHolderController.clear();
      _bicController.clear();
      _bankNameController.clear();
      return;
    }

    if (newData != null && newData != oldData) {
      final hasIbanChange = newData.iban != _ibanController.text;
      final hasHolderChange = newData.accountHolder != _accountHolderController.text;
      final hasBicChange = (newData.bic ?? '') != _bicController.text;
      final hasBankNameChange = (newData.bankName ?? '') != _bankNameController.text;

      if (hasIbanChange) _ibanController.text = newData.iban;
      if (hasHolderChange) _accountHolderController.text = newData.accountHolder;
      if (hasBicChange) _bicController.text = newData.bic ?? '';
      if (hasBankNameChange) _bankNameController.text = newData.bankName ?? '';

      if (hasIbanChange || hasHolderChange || hasBicChange || hasBankNameChange) {
        WidgetsBinding.instance.addPostFrameCallback((_) => _emitIfValid());
      }
    }
  }

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

    return Form(
      key: _formKey,
      onChanged: _emitIfValid,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _ibanController,
            decoration: getInputDecoration(context, l10n.iban, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (val) => (val == null || val.isEmpty) ? l10n.enterIban : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _accountHolderController,
            decoration: getInputDecoration(context, l10n.accountHolder, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (val) => (val == null || val.isEmpty) ? l10n.enterAccountHolder : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _bicController,
            decoration: getInputDecoration(context, l10n.bic, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (val) => (val == null || val.isEmpty) ? l10n.enterBic : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _bankNameController,
            decoration: getInputDecoration(context, l10n.bankName, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (val) => (val == null || val.isEmpty) ? l10n.enterBankName : null,
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _ibanController.dispose();
    _accountHolderController.dispose();
    _bicController.dispose();
    _bankNameController.dispose();
    super.dispose();
  }
}
