import 'dart:async';

import 'package:flutter/material.dart';
import 'package:initial_folder/models/detail_invoice_model.dart';
import 'package:initial_folder/services/detail_invoice_service.dart';
import 'package:provider/provider.dart';

enum ResultState { loading, noData, hasData, error }

class StreamInvoiceProvider extends ChangeNotifier {
  final DetailInvoiceService _detailInvoiceService = DetailInvoiceService();
  List<DataDetailInvoiceModel>? _detailInvoice;
  String? _message;
  String? _thumbnail;
  ResultState? _state;
  final StreamController<String> _transactionStatusController =
      StreamController<String>.broadcast();

  Stream<String> get transactionStatusStream =>
      _transactionStatusController.stream;
  String? get message => _message;
  String? get thumbnail => _thumbnail;
  List<DataDetailInvoiceModel>? get detailInvoice => _detailInvoice;
  ResultState? get state => _state;

  set selectedThumbnail(String? value) {
    _thumbnail = value;
    notifyListeners();
  }

  Future<void> fetchDetailInvoice(String? orderId) async {
    print("Fetching detail invoice for order ID: $orderId");
    try {
      _state = ResultState.loading;
      notifyListeners();
      final data = await _detailInvoiceService.detailInvoice(orderId);
      if (data.isEmpty) {
        _state = ResultState.noData;
        _message = 'Invoice Detail is Empty';
        print("Invoice detail is empty");
      } else {
        _state = ResultState.hasData;
        _detailInvoice = data;
        print(
            "Invoice detail fetched, updating transaction status to: ${data[0].transactionStatus}");
        _transactionStatusController.sink.add(data[0].transactionStatus!);
      }
    } catch (e) {
      _state = ResultState.error;
      _message = 'Error -> $e';
      print("Error fetching invoice detail: $e");
    }
    notifyListeners();
  }

  @override
  void dispose() {
    _transactionStatusController.close();
    super.dispose();
  }
}
