import 'package:flutter/foundation.dart';

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

import 'package:pweb/utils/report/operations/document_rule.dart';


class PaymentDetailsController extends ChangeNotifier {
  PaymentDetailsController({required String paymentRef})
    : _paymentRef = paymentRef;

  PaymentsProvider? _payments;
  String _paymentRef;
  Payment? _payment;

  String get paymentId => _paymentRef;
  Payment? get payment => _payment;
  bool get isLoading => _payments?.isLoading ?? false;
  Exception? get error => _payments?.error;

  OperationDocumentRef? operationDocumentRequest(
    PaymentExecutionOperation operation,
  ) {
    final current = _payment;
    if (current == null) return null;

    final operationRef = operation.operationRef;
    if (operationRef == null || operationRef.isEmpty) return null;
    final gatewayService = operation.gateway;
    if (gatewayService == null || gatewayService.isEmpty) return null;

    if (!isOperationDocumentEligible(operation.code)) return null;

    return OperationDocumentRef(
      gatewayService: gatewayService,
      operationRef: operationRef,
    );
  }

  bool canDownloadOperationDocument(PaymentExecutionOperation operation) =>
      operationDocumentRequest(operation) != null;

  void update(PaymentsProvider provider, String paymentId) {
    if (_paymentRef != paymentId) {
      _paymentRef = paymentId;
    }

    if (!identical(_payments, provider)) {
      _payments = provider;
    }

    _rebuild();
  }

  Future<void> refresh() async {
    await _payments?.refresh();
  }

  void _rebuild() {
    _payment = _findPayment(_payments?.payments ?? const [], _paymentRef);
    notifyListeners();
  }

  Payment? _findPayment(List<Payment> payments, String paymentId) {
    final trimmed = paymentId.trim();
    if (trimmed.isEmpty) return null;
    for (final payment in payments) {
      if (payment.paymentRef == trimmed) return payment;
    }
    return null;
  }
}
