import 'package:flutter/material.dart';

import 'package:pshared/models/payment/methods/type.dart';

import 'package:pweb/pages/payment_methods/icon.dart';

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


class PaymentMethodTile extends StatelessWidget {
  const PaymentMethodTile({
    super.key,
    required this.method,
    required this.index,
    required this.makeMain,
    required this.toggleEnabled,
    required this.edit,
    required this.delete,
  });

  final PaymentMethod method;
  final int index;
  final VoidCallback makeMain;
  final ValueChanged<bool> toggleEnabled;
  final VoidCallback edit;
  final VoidCallback delete;

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final theme = Theme.of(context);

    return Opacity(
      opacity: method.isArchived ? 1 : 0.5,
      child: Card(
        margin: const EdgeInsets.symmetric(vertical: 4),
        elevation: 0,
        child: ListTile(
          key: ValueKey(method.id),
          leading: Icon(iconForPaymentType(method.type)),
          onTap: makeMain,
          title: Row(
            children: [
              Expanded(child: Text(method.name)),
              if (method.description != null)
                Text(
                  method.description!,
                  style: theme.textTheme.bodySmall,
                ),
            ],
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildMakeMainButton(context),
              _buildEnabledSwitch(),
              _buildPopupMenu(l10n),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMakeMainButton(BuildContext context) {
    final theme = Theme.of(context);
    return IconButton(
      tooltip: AppLocalizations.of(context)!.makeMain,
      icon: Icon(
        method.isMain ? Icons.star : Icons.star_outline,
        color: method.isMain ? theme.colorScheme.primary : null,
      ),
      onPressed: makeMain,
    );
  }

  Widget _buildEnabledSwitch() => Switch.adaptive(
    value: method.isArchived,
    onChanged: toggleEnabled,
  );

  Widget _buildPopupMenu(AppLocalizations l10n) {
    return PopupMenuButton<String>(
      tooltip: l10n.moreActions,
      onSelected: (value) {
        switch (value) {
          case 'edit':
            edit();
            break;
          case 'delete':
            delete();
            break;
        }
      },
      itemBuilder: (_) => [
        PopupMenuItem(value: 'edit', child: Text(l10n.edit)),
        PopupMenuItem(value: 'delete', child: Text(l10n.delete)),
      ],
    );
  }
}
