import 'package:flutter/material.dart';

import 'package:flutter_multi_formatter/flutter_multi_formatter.dart';

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

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

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


class CardFormMinimal extends StatefulWidget {
  final void Function(CardPaymentMethod) onChanged;
  final CardPaymentMethod? initialData;
  final bool isEditable;

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

  @override
  State<CardFormMinimal> createState() => _CardFormMinimalState();
}

class _CardFormMinimalState extends State<CardFormMinimal> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _panController;
  late TextEditingController _firstNameController;
  late TextEditingController _lastNameController;

  @override
  void initState() {
    super.initState();
    _panController = TextEditingController(text: widget.initialData?.pan ?? '');
    _firstNameController = TextEditingController(text: widget.initialData?.firstName ?? '');
    _lastNameController = TextEditingController(text: widget.initialData?.lastName ?? '');

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

  void _emitIfValid() {
    if (_formKey.currentState?.validate() ?? false) {
      widget.onChanged(
        CardPaymentMethod(
          pan: _panController.text.replaceAll(' ', ''),
          firstName: _firstNameController.text,
          lastName: _lastNameController.text,
        ),
      );
    }
  }

  @override
  void didUpdateWidget(covariant CardFormMinimal oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialData == null && oldWidget.initialData != null) {
      _panController.clear();
      _firstNameController.clear();
      _lastNameController.clear();
    }
  }

  @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: _panController,
            decoration: getInputDecoration(context, l10n.cardNumber, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            keyboardType: TextInputType.number,
            inputFormatters: [CreditCardNumberInputFormatter()],
            validator: (v) => (v == null || v.replaceAll(' ', '').length < 12) ? l10n.enterCardNumber : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _firstNameController,
            decoration: getInputDecoration(context, l10n.firstName, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (v) => (v == null || v.isEmpty) ? l10n.enterFirstName : null,
          ),
          const SizedBox(height: 12),
          TextFormField(
            readOnly: !widget.isEditable,
            controller: _lastNameController,
            decoration: getInputDecoration(context, l10n.lastName, widget.isEditable),
            style: getTextFieldStyle(context, widget.isEditable),
            validator: (v) => (v == null || v.isEmpty) ? l10n.enterLastName : null,
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _panController.dispose();
    _firstNameController.dispose();
    _lastNameController.dispose();
    super.dispose();
  }
}
