import 'package:flutter/material.dart';

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

import 'package:pweb/pages/payment_methods/add/method_selector.dart';
import 'package:pweb/pages/payment_methods/form.dart';
import 'package:pweb/utils/payment/availability.dart';

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


class AddPaymentMethodDialog extends StatefulWidget {
  const AddPaymentMethodDialog({super.key});

  @override
  State<AddPaymentMethodDialog> createState() => _AddPaymentMethodDialogState();
}

class _AddPaymentMethodDialogState extends State<AddPaymentMethodDialog> {
  final _formKey = GlobalKey<FormState>();
  PaymentType? _selectedType;

  // Holds current result from the selected form
  Object? _currentMethod;

  void _submit() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

      if (_currentMethod case final Object method) {
        Navigator.of(context).pop(method);
      }
    }
  }

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

    return AlertDialog(
      title: Text(l10n.addPaymentMethod),
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              PaymentMethodTypeSelector(
                value: _selectedType,
                types: visiblePaymentTypes,
                disabledTypes: disabledPaymentTypes,
                onChanged: (val) => setState(() {
                  _selectedType = val;
                  _currentMethod = null;
                }),
              ),
              const SizedBox(height: 16),
              if (_selectedType != null)
                PaymentMethodForm(
                  selectedType: _selectedType,
                  onChanged: (val) => _currentMethod = val,
                ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: Text(l10n.cancel),
        ),
        ElevatedButton(
          onPressed: _submit,
          child: Text(l10n.add),
        ),
      ],
    );
  }
}
