import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc;
import 'package:krow_data_connect/krow_data_connect.dart' as dc;

/// Card showing the current payment method.
class PaymentMethodCard extends StatefulWidget {
  /// Creates a [PaymentMethodCard].
  const PaymentMethodCard({super.key});

  @override
  State<PaymentMethodCard> createState() => _PaymentMethodCardState();
}

class _PaymentMethodCardState extends State<PaymentMethodCard> {
  late final Future<dc.GetAccountsByOwnerIdData?> _accountsFuture =
      _loadAccounts();

  Future<dc.GetAccountsByOwnerIdData?> _loadAccounts() async {
    final String? businessId =
        dc.ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return null;
    }

    final fdc.QueryResult<
      dc.GetAccountsByOwnerIdData,
      dc.GetAccountsByOwnerIdVariables
    >
    result = await dc.ExampleConnector.instance
        .getAccountsByOwnerId(ownerId: businessId)
        .execute();
    return result.data;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<dc.GetAccountsByOwnerIdData?>(
      future: _accountsFuture,
      builder:
          (
            BuildContext context,
            AsyncSnapshot<dc.GetAccountsByOwnerIdData?> snapshot,
          ) {
            final List<dc.GetAccountsByOwnerIdAccounts> accounts =
                snapshot.data?.accounts ?? <dc.GetAccountsByOwnerIdAccounts>[];
            final dc.GetAccountsByOwnerIdAccounts? account = accounts.isNotEmpty
                ? accounts.first
                : null;

            if (account == null) {
              return const SizedBox.shrink();
            }

            final String bankLabel = account.bank.isNotEmpty == true
                ? account.bank
                : '----';
            final String last4 = account.last4.isNotEmpty == true
                ? account.last4
                : '----';
            final bool isPrimary = account.isPrimary ?? false;
            final String expiryLabel = _formatExpiry(account.expiryTime);

            return Container(
              padding: const EdgeInsets.all(UiConstants.space4),
              decoration: BoxDecoration(
                color: UiColors.white,
                borderRadius: UiConstants.radiusLg,
                border: Border.all(color: UiColors.border),
                boxShadow: <BoxShadow>[
                  BoxShadow(
                    color: UiColors.black.withValues(alpha: 0.04),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        t.client_billing.payment_method,
                        style: UiTypography.title2b.textPrimary,
                      ),
                      const SizedBox.shrink(),
                    ],
                  ),
                  const SizedBox(height: UiConstants.space3),
                  Container(
                    padding: const EdgeInsets.all(UiConstants.space3),
                    decoration: BoxDecoration(
                      color: UiColors.bgSecondary,
                      borderRadius: UiConstants.radiusMd,
                    ),
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: 40,
                          height: 28,
                          decoration: BoxDecoration(
                            color: UiColors.primary,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Center(
                            child: Text(
                              bankLabel,
                              style: const TextStyle(
                                color: UiColors.white,
                                fontSize: 10,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                        const SizedBox(width: UiConstants.space3),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                '•••• $last4',
                                style: UiTypography.body2b.textPrimary,
                              ),
                              Text(
                                t.client_billing.expires(date: expiryLabel),
                                style: UiTypography.footnote2r.textSecondary,
                              ),
                            ],
                          ),
                        ),
                        if (isPrimary)
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: UiColors.accent,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              t.client_billing.default_badge,
                              style: UiTypography.titleUppercase4b.textPrimary,
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
    );
  }

  String _formatExpiry(fdc.Timestamp? expiryTime) {
    if (expiryTime == null) {
      return 'N/A';
    }
    final DateTime date = expiryTime.toDateTime();
    final String month = date.month.toString().padLeft(2, '0');
    final String year = (date.year % 100).toString().padLeft(2, '0');
    return '$month/$year';
  }
}
