import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/payment/source_type.dart';
import 'package:pshared/provider/payment/payments.dart';

import 'package:pweb/controllers/operations/report_operations.dart';
import 'package:pweb/models/state/load_more_state.dart';
import 'package:pweb/pages/report/cards/list.dart';
import 'package:pweb/pages/report/operations/actions.dart';
import 'package:pweb/pages/report/operations/states/error.dart';
import 'package:pweb/pages/report/operations/states/loading.dart';

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


class WalletHistory extends StatelessWidget {
  final String sourceRef;
  final PaymentSourceType sourceType;
  final List<String> sourceRefs;

  const WalletHistory({
    super.key,
    required this.sourceRef,
    required this.sourceType,
    required this.sourceRefs,
  });

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<
      PaymentsProvider,
      ReportOperationsController
    >(
      create: (_) => ReportOperationsController(),
      update: (_, payments, controller) => controller!
        ..update(
          payments,
          sourceType: sourceType,
          sourceRef: sourceRef,
          sourceRefs: sourceRefs,
        ),
      child: const _WalletHistoryContent(),
    );
  }
}

class _WalletHistoryContent extends StatelessWidget {
  const _WalletHistoryContent();

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

    return Consumer<ReportOperationsController>(
      builder: (context, controller, child) {
        if (controller.isLoading) {
          return const OperationHistoryLoading();
        }

        if (controller.error != null) {
          final message =
              controller.error?.toString() ?? loc.noErrorInformation;
          return OperationHistoryError(
            message: loc.notificationError(message),
            retryLabel: loc.retry,
            onRetry: controller.refresh,
          );
        }

        final hasLoadMore = controller.loadMoreState != LoadMoreState.hidden;
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              OperationsCardsList(
                operations: controller.filteredOperations,
                onTap: (operation) => openPaymentDetails(context, operation),
                loadMoreState: controller.loadMoreState,
                onLoadMore: hasLoadMore ? controller.loadMore : null,
              ),
            ],
          ),
        );
      },
    );
  }
}
