import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/resources.dart';
import 'package:pshared/provider/permissions.dart';

import 'package:pweb/controllers/invitations/page.dart';
import 'package:pweb/pages/invitations/widgets/header.dart';
import 'package:pweb/pages/invitations/widgets/form/form.dart';
import 'package:pweb/pages/invitations/widgets/list/list.dart';
import 'package:pweb/pages/loader.dart';

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


class InvitationsPageView extends StatelessWidget {
  final GlobalKey<FormState> formKey;
  final TextEditingController emailController;
  final TextEditingController firstNameController;
  final TextEditingController lastNameController;
  final TextEditingController messageController;
  final VoidCallback onSubmit;

  const InvitationsPageView({
    super.key,
    required this.formKey,
    required this.emailController,
    required this.firstNameController,
    required this.lastNameController,
    required this.messageController,
    required this.onSubmit,
  });

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context)!;
    final permissions = context.watch<PermissionsProvider>();
    final canCreateRoles = permissions.canCreate(ResourceType.roles);
    final ui = context.watch<InvitationsPageController>();

    if (!permissions.canRead(ResourceType.invitations)) {
      return PageViewLoader(
        child: Center(child: Text(loc.errorAccessDenied)),
      );
    }

    return PageViewLoader(
      child: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InvitationsHeader(loc: loc),
              const SizedBox(height: 16),
              InvitationsForm(
                formKey: formKey,
                emailController: emailController,
                firstNameController: firstNameController,
                lastNameController: lastNameController,
                messageController: messageController,
                canCreateRoles: canCreateRoles,
                expiryDays: ui.expiryDays,
                onExpiryChanged: ui.setExpiryDays,
                selectedRoleRef: ui.selectedRoleRef,
                onRoleChanged: ui.setSelectedRoleRef,
                canCreate: permissions.canCreate(ResourceType.invitations),
                onSubmit: onSubmit,
              ),
              const SizedBox(height: 24),
              const InvitationsList(),
            ],
          ),
        ),
      ),
    );
  }
}
