import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/permissions/action.dart' as perm;
import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/models/resources.dart';
import 'package:pshared/provider/permissions.dart';

import 'package:pweb/pages/address_book/page/recipient/item.dart';


class RecipientAddressBookList extends StatelessWidget {
  final List<Recipient> filteredRecipients;
  final ValueChanged<Recipient>? onSelected;
  final ValueChanged<Recipient>? onEdit;
  final ValueChanged<Recipient>? onDelete;

  const RecipientAddressBookList({
    super.key,
    required this.filteredRecipients,
    this.onSelected,
    this.onEdit,
    this.onDelete,
  });

  bool _checkPermissions(BuildContext context, Recipient recipient, perm.Action action) {
    return context.read<PermissionsProvider>().canAccessResource(
      ResourceType.recipients,
      action: action,
      objectRef: recipient.id,
    );
  }

  @override
  Widget build(BuildContext context) => ListView.builder(
    itemCount: filteredRecipients.length,
    itemBuilder: (context, index) {
      final recipient = filteredRecipients[index];
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 6.0), 
        child: RecipientAddressBookItem(
          recipient: recipient,
          onTap: () => onSelected?.call(recipient),
          onEdit: _checkPermissions(context, recipient, perm.Action.update)
            ? () => onEdit?.call(recipient)
            : null,
          onDelete: _checkPermissions(context, recipient, perm.Action.delete)
            ? () => onDelete?.call(recipient)
            : null,
        ),
      );
    },
  );
}
