import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gen_rentals/Services/api_calling.dart';
import 'package:path_provider/path_provider.dart'; //
import 'package:open_filex/open_filex.dart';
import '../Models/TransactionModels/PaymentReceiptDetailsResponse.dart';
import '../Models/TransactionModels/TransactionsResponse.dart';
import '../Services/api_post_request.dart';
import '../Utility/CustomSnackbar.dart';

class TransactionsProvider with ChangeNotifier {
  bool _isLoading = false;
  TransactionsResponse? _transactionsResponse;

  bool get isLoading => _isLoading;
  TransactionsResponse? get transactionsResponse => _transactionsResponse;

  /// For UI convenience
  Map<String, List<TransactionItem>> get transactionsByMonth =>
      _transactionsResponse?.transactions ?? {};

  /// Fetch Rental Transactions API
  Future<void> fetchRentalTransactions(String sessionId, String accId) async {
    _isLoading = true;
    notifyListeners();

    try {
      final response =
      await ApiCalling.fetchRentalsTransactionsApi(sessionId, accId);

      if (response != null && response.error == "0") {
        _transactionsResponse = response;
        log("✅ Transactions fetched successfully: ${response.transactions?.length ?? 0} months");
      } else {
        log("⚠️ Error in API response: ${response?.message}");
        _transactionsResponse = null;
      }
    } catch (e) {
      log("❌ Exception in fetchRentalTransactions: $e");
      _transactionsResponse = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Optional: Clear data
  void clearTransactions() {
    _transactionsResponse = null;
    notifyListeners();
  }



  ReceiptDetails? _receiptDetails;
  ReceiptDetails? get receiptDetails => _receiptDetails;

  /// Fetch payment receipt details
  Future<void> fetchPaymentReceiptDetails(
      String sessionId, String accId, String ledgerId) async {
    _isLoading = true;
    notifyListeners();

    try {
      final response = await ApiCalling.fetchPaymentReceiptDetailsApi(
        sessionId,
        accId,
        ledgerId,
      );

      if (response != null && response.error == 0) {
        _receiptDetails = response.receiptDetails;
        log("✅ Payment Receipt Fetched: ${_receiptDetails?.id}");
      } else {
        log("⚠️ Payment Receipt Error: ${response?.message}");
      }
    } catch (e) {
      log("❌ Provider Error (fetchPaymentReceiptDetails): $e");
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Clear old data
  void clearData() {
    _receiptDetails = null;
    notifyListeners();
  }




  bool _isDownloading = false;
  bool get isDownloading => _isDownloading;

  void setDownloading(bool value) {
    _isDownloading = value;
    notifyListeners();
  }

  ///  Download Payment Receipt
  Future<void> downloadPaymentReceipt(
      BuildContext context,
      String sessionId,
      String ledgerId,
      String accId,
      ) async {
    setDownloading(true);
    try {
      // Step 1: Call paymentReceiptDownloadApi to get file URL/path
      final res = await ApiCalling.paymentReceiptDownloadApi(sessionId, ledgerId, accId);
      if (res == null || res.error != 0 || res.filePath == null) {
        CustomSnackBar.showError(
          context: context,
          message: res?.message ?? "Download failed",
        );
        setDownloading(false);
        return;
      }

      final fileUrl = res.filePath!;
      final dir = await getApplicationDocumentsDirectory();
      final savePath = '${dir.path}/payment_receipt_$ledgerId.pdf';

      // Step 2: Download file using helper
      final success = await downloadFile(fileUrl, savePath);

      if (success) {
        CustomSnackBar.showSuccess(
          context: context,
          message: "Payment receipt downloaded successfully!",
        );
        await OpenFilex.open(savePath);
      } else {
        CustomSnackBar.showError(
          context: context,
          message: "Failed to download payment receipt",
        );
      }
    } catch (e) {
      debugPrint("❌ Payment receipt download error: $e");
      CustomSnackBar.showError(
        context: context,
        message: "Error downloading payment receipt",
      );
    } finally {
      setDownloading(false);
    }
  }

  ///  File Downloader
  Future<bool> downloadFile(String apiUrl, String savePath) async {
    try {
      final response = await get(apiUrl, {}); // Using your shared GET helper
      if (response != null && response.statusCode == 200) {
        final file = File(savePath);
        await file.writeAsBytes(response.bodyBytes);
        return true;
      } else {
        debugPrint("❌ Failed to download file: ${response?.statusCode}");
        return false;
      }
    } catch (e) {
      debugPrint("❌ File download error: $e");
      return false;
    }
  }

}


