import 'package:flutter/material.dart';

import 'package:go_router/go_router.dart';

import 'package:provider/provider.dart';

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

import 'package:pweb/app/router/payout_routes.dart';
import 'package:pweb/controllers/payments/details.dart';
import 'package:pweb/pages/report/details/content.dart';
import 'package:pweb/pages/report/details/states/error.dart';
import 'package:pweb/pages/report/details/states/not_found.dart';
import 'package:pweb/utils/report/download_act.dart';

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


class PaymentDetailsPage extends StatelessWidget {
  final String paymentRef;

  const PaymentDetailsPage({super.key, required this.paymentRef});

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

class _PaymentDetailsView extends StatelessWidget {
  final String paymentRef;

  const _PaymentDetailsView({required this.paymentRef});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Consumer<PaymentDetailsController>(
        builder: (context, controller, child) {
          final loc = AppLocalizations.of(context)!;
          if (controller.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          if (controller.error != null) {
            return PaymentDetailsError(
              message: controller.error?.toString() ?? loc.noErrorInformation,
              onRetry: () => controller.refresh(),
            );
          }

          final payment = controller.payment;
          if (payment == null) {
            return PaymentDetailsNotFound(onBack: () => _handleBack(context));
          }

          return PaymentDetailsContent(
            payment: payment,
            onBack: () => _handleBack(context),
            canDownloadOperationDocument:
                controller.canDownloadOperationDocument,
            onDownloadOperationDocument: (operation) {
              final request = controller.operationDocumentRequest(operation);
              if (request == null) return;
              downloadPaymentAct(
                context,
                gatewayService: request.gatewayService,
                operationRef: request.operationRef,
                paymentRef: paymentRef,
              );
            },
          );
        },
      ),
    );
  }

  void _handleBack(BuildContext context) {
    final router = GoRouter.of(context);
    if (router.canPop()) {
      context.pop();
      return;
    }
    context.go(PayoutRoutes.reportsPath);
  }
}
