import 'package:flutter/material.dart';

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


Future<RoleDraft?> showCreateRoleDialog(BuildContext context) {
  return showDialog<RoleDraft>(
    context: context,
    builder: (dialogContext) => const _CreateRoleDialog(),
  );
}

class _CreateRoleDialog extends StatefulWidget {
  const _CreateRoleDialog();

  @override
  State<_CreateRoleDialog> createState() => _CreateRoleDialogState();
}

class _CreateRoleDialogState extends State<_CreateRoleDialog> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  void _submit() {
    final form = _formKey.currentState;
    if (form == null || !form.validate()) return;
    Navigator.of(context).pop(RoleDraft(
      name: _nameController.text.trim(),
      description: _descriptionController.text.trim(),
    ));
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context)!;
    return AlertDialog(
      title: Text(loc.invitationAddRoleTitle),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              controller: _nameController,
              decoration: InputDecoration(
                labelText: loc.invitationRoleNameLabel,
              ),
              validator: (value) => (value == null || value.trim().isEmpty)
                ? loc.invitationRoleNameRequired
                : null,
            ),
            const SizedBox(height: 12),
            TextFormField(
              controller: _descriptionController,
              minLines: 2,
              maxLines: 3,
              decoration: InputDecoration(
                labelText: loc.invitationRoleDescriptionLabel,
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: Text(loc.cancel),
        ),
        ElevatedButton(
          onPressed: _submit,
          child: Text(loc.add),
        ),
      ],
    );
  }
}
