import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

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

import 'package:pweb/pages/dashboard/payouts/multiple/sections/history/header.dart';
import 'package:pweb/controllers/payments/recent_payments.dart';
import 'package:pweb/pages/report/cards/column.dart';
import 'package:pweb/utils/report/payment_mapper.dart';
import 'package:pweb/app/router/payout_routes.dart';

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


class UploadHistorySection extends StatelessWidget {
  const UploadHistorySection({super.key});

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

class _RecentPaymentsView extends StatelessWidget {
  const _RecentPaymentsView();

  void _openPaymentDetails(BuildContext context, OperationItem operation) {
    final paymentId = paymentIdFromOperation(operation);
    if (paymentId == null) return;
    context.pushToReportPayment(paymentId);
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final l10 = AppLocalizations.of(context)!;
    return Consumer<RecentPaymentsController>(
      builder: (context, controller, child) {
        if (controller.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        if (controller.error != null) {
          return Text(
            l10.notificationError(controller.error ?? l10.noErrorInformation),
          );
        }

        return Column(
          children: [
            UploadHistoryHeader(theme: theme),
            const SizedBox(height: 8),
            OperationsCardsColumn(
              operations: controller.recentOperations,
              onTap: (operation) => _openPaymentDetails(context, operation),
            ),
          ],
        );
      },
    );
  }
}
