import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/provider/organizations.dart';
import 'package:pshared/provider/recipient/pmethods.dart';

import 'package:pweb/pages/dashboard/payouts/single/address_book/avatar.dart';
import 'package:pweb/pages/dashboard/payouts/single/address_book/long_list/info_row.dart';
import 'package:pweb/utils/payment/label.dart';


class RecipientItem extends StatefulWidget {
  static const double _horizontalPadding = 16.0;
  static const double _verticalPadding = 8.0;
  static const double _avatarRadius = 20;
  static const double _spacingWidth = 12;

  final Recipient recipient;
  final VoidCallback onTap;

  const RecipientItem({
    super.key,
    required this.recipient,
    required this.onTap,
  });

  @override
  State<RecipientItem> createState() => _RecipientItemState();
}

class _RecipientItemState extends State<RecipientItem> {
  late PaymentMethodsProvider _methodsProvider;

  @override
  void initState() {
    super.initState();
    _methodsProvider = PaymentMethodsProvider()
      ..addListener(_onProviderChanged)
      ..loadMethods(
        context.read<OrganizationsProvider>(), 
        widget.recipient.id,
      );
  }


  @override
  void dispose() {
    _methodsProvider.removeListener(_onProviderChanged);
    _methodsProvider.dispose();
    super.dispose();
  }

  void _onProviderChanged() => setState(() {});

  @override
  Widget build(BuildContext context) {
    if (!_methodsProvider.isReady) return const Center(child: CircularProgressIndicator());

    final recipient = widget.recipient;
    return InkWell(
      onTap: widget.onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: RecipientItem._horizontalPadding,
          vertical: RecipientItem._verticalPadding,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ListTile(
                contentPadding: EdgeInsets.zero,
                leading: RecipientAvatar(
                  isVisible: false,
                  name: recipient.name,
                  avatarUrl: recipient.avatarUrl,
                  avatarRadius: RecipientItem._avatarRadius,
                  nameStyle: Theme.of(context).textTheme.bodyMedium,
                ),
                title: Text(recipient.name),
                subtitle: Text(recipient.email),
              ),
            ),
            const SizedBox(width: RecipientItem._spacingWidth),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: _methodsProvider.methods.map((m) => PaymentInfoRow(
                label: getPaymentTypeLabel(context, m.type),
                value: getPaymentTypeDescription(context, m),
              )).toList(),
            ),
          ],
        ),
      ),
    );
  }
}
