import 'dart:async';
import 'package:flutter/material.dart';
import '../Models/ordersModels/commonResponse.dart';
import '../Utils/custom_snackbar.dart';
import '../services/api_calling.dart';

class QrProvider extends ChangeNotifier {
  CommonResponse? _qrResponse;
  bool _isLoading = false;
  String? _errorMessage;
  int _secondsLeft = 120; // 2 minutes

  CommonResponse? get qrResponse => _qrResponse;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  int get secondsLeft => _secondsLeft;

  Timer? _timer;

  Future<void> fetchRazorpayQr({
    required String sessionId,
    required String empId,
    required String amount,
    required String refType,
    required String refId,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ApiCalling.fetchRazorpayUpiQrApi(
        sessionId,
        empId,
        amount,
        refType,
        refId,
      );

      if (response != null && response.error == "0") {
        _qrResponse = response;
        _startTimer();
      } else {
        _errorMessage = response?.message ?? "Something went wrong";
      }
    } catch (e) {
      _errorMessage = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  void _startTimer() {
    _secondsLeft = 120;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_secondsLeft > 0) {
        _secondsLeft--;
        notifyListeners();
      } else {
        timer.cancel();
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  bool _isPaymentUpdating = false;
  bool get isPaymentUpdating => _isPaymentUpdating;

  set isPaymentUpdating(bool value) {
    _isPaymentUpdating = value;
    notifyListeners();
  }

  /// Fetch Razorpay QR Payment Status
  /// NOTE: This method no longer shows snackbars itself. It simply returns the response.
  Future<CommonResponse?> fetchRazorpayUpiQrStatus({
    required BuildContext context,
    required String sessionId,
    required String empId,
    required String razorpayOrderId,
  }) async {
    try {
      isPaymentUpdating = true;

      final response = await ApiCalling.fetchRazorpayUpiQrStatusApi(
        sessionId,
        empId,
        razorpayOrderId,
      );

      if (response != null) {
        if (response.sessionExists == 1 && response.error == "0") {
          debugPrint("Payment Status: ${response.message}");
        } else {
          // IMPORTANT: do not show UI here (no repeated warnings).
          // The caller (screen) should decide when to show failure messages.
          debugPrint("Payment still pending or failed: ${response.message}");
        }
      } else {
        debugPrint("Null response from Razorpay QR Status API");
      }

      return response;
    } catch (e) {
      debugPrint("fetchRazorpayUpiQrStatus error: $e");
      return null;
    } finally {
      isPaymentUpdating = false;
    }
  }
}
