import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:glowwheels/constants/api.dart';
import 'package:glowwheels/models/order_model.dart';
import 'package:http/http.dart' as http;

class OrdersProvider with ChangeNotifier {
  List<Order> _orders = [];
  bool _isLoading = false;
  bool _isRefreshing = false;
  String? _errorMessage;

  List<Order> get orders => _orders;
  bool get isLoading => _isLoading;
  bool get isRefreshing => _isRefreshing;
  String? get errorMessage => _errorMessage;

  Future<void> fetchOrders(String shopId, {bool refresh = false}) async {
    final ordersUri = Uri.parse(ApiConstants.ordersByShop(shopId));

    if (refresh) {
      _isRefreshing = true;
    } else {
      _isLoading = true;
    }
    notifyListeners();

    try {
      final response = await http.get(ordersUri);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data['success'] == true) {
          final List<dynamic> ordersJson = data['orders'];
          _orders = ordersJson.map((orderJson) => Order.fromJson(orderJson)).toList();
          _errorMessage = null;
        } else {
          _errorMessage = 'Failed to fetch orders';
        }
      } else {
        _errorMessage = 'Server error: ${response.statusCode}';
      }
    } catch (e) {
      _errorMessage = 'An error occurred: $e';
    }

    _isLoading = false;
    _isRefreshing = false;
    notifyListeners();
  }

  Future<void> assignServiceBoyToOrder({
    required String orderId,
    required String serviceBoyId,
    required String shopId,
  }) async {
    final assignUri = Uri.parse(ApiConstants.assignServiceBoy(orderId));

    try {
      final response = await http.put(
        assignUri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'serviceBoyId': serviceBoyId}),
      );

      if (response.statusCode == 200) {
        print('Successfully assigned service boy');
      } else {
        print('Failed to assign service boy: ${response.statusCode}');
      }
    } catch (e) {
      print('Error assigning service boy: $e');
    }
  }

  Future<void> updateOrderStatus({
    required String orderId,
    required String status,
  }) async {
    final updateStatusUri = Uri.parse(ApiConstants.updateOrderStatusByAdmin(orderId));

    try {
      final response = await http.put(
        updateStatusUri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'status': status}),
      );

      if (response.statusCode == 200) {
        final index = _orders.indexWhere((o) => o.id == orderId);
        if (index != -1) {
          _orders[index] = _orders[index].copyWith(status: status);
          notifyListeners();
        }
      } else {
        print('Failed to update status: ${response.statusCode}');
      }
    } catch (e) {
      print('Error updating order status: $e');
    }
  }
}
