import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pweb/controllers/invitations/page.dart';
import 'package:pweb/pages/invitations/page/providers.dart';
import 'package:pweb/pages/invitations/page/view.dart';
import 'package:pweb/utils/error/snackbar.dart';

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


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

  @override
  State<InvitationsPage> createState() => _InvitationsPageState();
}

class _InvitationsPageState extends State<InvitationsPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _lastNameController = TextEditingController();
  final TextEditingController _messageController = TextEditingController();

  Future<void> _sendInvitation(BuildContext context) async {
    final form = _formKey.currentState;
    if (form == null || !form.validate()) return;

    final loc = AppLocalizations.of(context)!;

    await executeActionWithNotification(
      context: context,
      action: () => context.read<InvitationsPageController>().sendInvitation(
        email: _emailController.text,
        name: _firstNameController.text,
        lastName: _lastNameController.text,
        comment: _messageController.text,
      ),
      successMessage: loc.invitationCreatedSuccess,
      errorMessage: loc.errorCreatingInvitation,
    );

    _emailController.clear();
    _firstNameController.clear();
    _lastNameController.clear();
    _messageController.clear();
  }

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

  @override
  Widget build(BuildContext context) {
    return InvitationsPageProviders(
      child: Builder(
        builder: (context) => InvitationsPageView(
          formKey: _formKey,
          emailController: _emailController,
          firstNameController: _firstNameController,
          lastNameController: _lastNameController,
          messageController: _messageController,
          onSubmit: () => _sendInvitation(context),
        ),
      ),
    );
  }
}
