import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:gen_rentals/Services/api_calling.dart';
import 'package:gen_rentals/Utility/CustomSnackbar.dart';
import '../Models/BillsModels/BillDetailsResponse.dart';
import '../Models/BillsModels/billListResponse.dart';
import 'package:path_provider/path_provider.dart'; //
import 'package:open_filex/open_filex.dart';

import '../Services/api_post_request.dart'; //


class BillProvider extends ChangeNotifier {
  bool _isLoading = false;
  BillListResponse? _billListResponse;

  bool get isLoading => _isLoading;
  BillListResponse? get billListResponse => _billListResponse;
  List<Bills> get bills => _billListResponse?.bills ?? [];
  LatestBill? get latestBill => _billListResponse?.latestBill;

  /// Fetch Bill List
  Future<void> fetchBillList(
      String sessionId, String orderId, String accId) async {
    try {
      _isLoading = true;
      notifyListeners();

      final response = await ApiCalling.fetchBillListApi(
        sessionId,
        orderId,
        accId,
      );

      if (response != null && response.error == 0) {
        _billListResponse = response;
      } else {
        _billListResponse = null;
        debugPrint("❌ API Error: ${response?.message}");
      }
    } catch (e) {
      debugPrint("❌ Exception in BillProvider: $e");
      _billListResponse = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Clear Data
  void clearData() {
    _billListResponse = null;
    notifyListeners();
  }






  /// Bill Details
  BillDetails? _billDetails;
  BillDetails? get billDetails => _billDetails;



  bool _isDetailsLoading = false;
  bool get isDetailsLoading => _isDetailsLoading;

  /// Error message (optional)
  String? _errorMessage;
  String? get errorMessage => _errorMessage;




  /// Fetch details for a specific bill
  Future<void> fetchBillDetails(String sessionId, String accId, String billId) async {
    try {
      _isDetailsLoading = true;
      _errorMessage = null;
      notifyListeners();

      final response = await ApiCalling.fetchBillDetailsApi(sessionId, accId, billId);

      if (response != null && response.error == 0) {
        _billDetails = response.billDetails;
      } else {
        _errorMessage = response?.message ?? "Unable to load bill details";
      }
    } catch (e) {
      _errorMessage = e.toString();
      debugPrint("❌ Error (fetchBillDetails): $e");
    } finally {
      _isDetailsLoading = false;
      notifyListeners();
    }
  }

  /// Clear bill details (optional, if you navigate away from details screen)
  void clearBillDetails() {
    _billDetails = null;
    notifyListeners();
  }


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

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

  /// 🧾 Download Bill
  Future<void> downloadBill(BuildContext context,
      String sessionId, String billId, String accId) async {
    setDownloading(true);
    try {
      // Step 1: Call billDownloadApi to get file path
      final res = await ApiCalling.billDownloadApi(sessionId, billId, accId);
      if (res == null || res.error != 0 || res.filePath == null) {
        // showToast(res?.message ?? "Download failed");
        setDownloading(false);
        return;
      }

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

      // Step 2: Download file
      final success = await downloadFile(fileUrl, savePath);
      if (success) {
        CustomSnackBar.showSuccess(
            context: context,
            message: "File downloaded successfully!"
        );
        // showToast("File downloaded successfully!");
        await OpenFilex.open(savePath);
      } else {
        CustomSnackBar.showError(
            context: context,
            message: "Failed to download file"
        );
        // showToast("Failed to download file");
      }
    } catch (e) {
      debugPrint("❌ Bill download error: $e");
      CustomSnackBar.showError(
          context: context,
          message: "Error downloading file"
      );
      // showToast("Error downloading file");

    } finally {
      setDownloading(false);
    }
  }

  ///  File Downloader
  Future<bool> downloadFile(String apiUrl, String savePath) async {
    try {
      final response = await get(apiUrl, {}); //  Using your 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;
    }
  }

}



