import 'package:flutter/material.dart';

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

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

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


class LedgerForm extends StatefulWidget {
  final void Function(LedgerPaymentMethod) onChanged;
  final LedgerPaymentMethod? initialData;
  final bool isEditable;

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

  @override
  State<LedgerForm> createState() => _LedgerFormState();
}

class _LedgerFormState extends State<LedgerForm> {
  final _formKey = GlobalKey<FormState>();

  late final TextEditingController _ledgerAccountRefController;
  late final TextEditingController _contraLedgerAccountRefController;

  @override
  void initState() {
    super.initState();
    _ledgerAccountRefController = TextEditingController(
      text: widget.initialData?.ledgerAccountRef ?? '',
    );
    _contraLedgerAccountRefController = TextEditingController(
      text: widget.initialData?.contraLedgerAccountRef ?? '',
    );

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

  void _emitIfValid() {
    if (_formKey.currentState?.validate() ?? false) {
      final contraRef = _contraLedgerAccountRefController.text.trim();
      widget.onChanged(
        LedgerPaymentMethod(
          ledgerAccountRef: _ledgerAccountRefController.text.trim(),
          contraLedgerAccountRef: contraRef.isEmpty ? null : contraRef,
        ),
      );
    }
  }

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

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

    if (newData != null && newData != oldData) {
      final hasLedgerRefChange = newData.ledgerAccountRef != _ledgerAccountRefController.text;
      final hasContraRefChange = (newData.contraLedgerAccountRef ?? '') != _contraLedgerAccountRefController.text;

      if (hasLedgerRefChange) _ledgerAccountRefController.text = newData.ledgerAccountRef;
      if (hasContraRefChange) {
        _contraLedgerAccountRefController.text = newData.contraLedgerAccountRef ?? '';
      }

      if (hasLedgerRefChange || hasContraRefChange) {
        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: _ledgerAccountRefController,
            decoration: getInputDecoration(context, l10n.ledgerAccountRef, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (val) => (val == null || val.trim().isEmpty)
                ? l10n.enterLedgerAccountRef
                : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _contraLedgerAccountRefController,
            decoration: getInputDecoration(context, l10n.contraLedgerAccountRef, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _ledgerAccountRefController.dispose();
    _contraLedgerAccountRefController.dispose();
    super.dispose();
  }
}
