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

class ServiceBoyProvider with ChangeNotifier {
  List<ServiceBoy> _serviceBoys = [];
  ServiceBoy? _selectedBoy;
  bool _isLoading = false;

  List<ServiceBoy> get serviceBoys => _serviceBoys;
  ServiceBoy? get selectedBoy => _selectedBoy;
  bool get isLoading => _isLoading;

  /// Fetch service boys by shop ID
  Future<void> fetchServiceBoys(String shopId) async {
    _isLoading = true;
    notifyListeners();
    final serviceBoyListUri = Uri.parse(ApiConstants.serviceBoysByShop(shopId));

    try {
      final response = await http.get(serviceBoyListUri);
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        final List<dynamic> boysJson = data['data']['serviceBoy'];
        _serviceBoys = boysJson.map((json) => ServiceBoy.fromJson(json)).toList();
        print('fetched service boys');
        print (_serviceBoys);
        notifyListeners();
      } else {
        print('Failed to fetch service boys: ${response.statusCode}');
      }
    } catch (e) {
      print('Error fetching service boys: $e');
    }
    _isLoading = false;
    notifyListeners();
  }

  /// Fetch a single service boy by ID
  Future<ServiceBoy?> fetchServiceBoyById(String serviceBoyId) async {
    final serviceBoyUri = Uri.parse(ApiConstants.serviceBoyDetails(serviceBoyId));

    try {
      final response = await http.get(serviceBoyUri);
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        final boyJson = data['data']; // Adjust if API wraps in `data`
        final serviceBoy = ServiceBoy.fromJson(boyJson);
        return serviceBoy;
      } else {
        print('Failed to fetch service boy: ${response.statusCode}');
      }
    } catch (e) {
      print('Error fetching service boy: $e');
    }
    return null;
  }

  /// Add new service boy to shop
  Future<void> addServiceBoy(String shopId, String name,String phone) async {
    print('add api called');
    print(name+'Phone '+phone.toString());
    final addServiceBoyUri = Uri.parse(ApiConstants.addServiceBoy);
    final body = jsonEncode({
      'shopId': shopId,
      'serviceBoy': [
        {
          'name': name,
          'phone':phone,
        }
      ]
    });

    try {
      final response = await http.post(
        addServiceBoyUri,
        headers: {'Content-Type': 'application/json'},
        body: body,
      );
      print('add service boy response '+response.statusCode.toString());
      if (response.statusCode == 200) {
        await fetchServiceBoys(shopId); // refresh list
      } else {
        print('Failed to add service boy: ${response.statusCode}');
      }
    } catch (e) {
      print('Error adding service boy: $e');
    }
  }

  /// Edit service boy phone
  Future<void> editServiceBoy(
      String serviceBoyId,
      String updatedName,
      String updatedPhone,
      String shopId,
      ) async {
    final serviceBoyUri = Uri.parse(ApiConstants.serviceBoyDetails(serviceBoyId));

    // Build request body only with non-empty fields
    final Map<String, dynamic> data = {};
    if (updatedName.isNotEmpty) data['name'] = updatedName;
    if (updatedPhone.isNotEmpty) data['phone'] = updatedPhone;

    if (data.isEmpty) {
      print('No fields to update.');
      return;
    }

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

      if (response.statusCode == 200) {
        print('Service boy updated successfully');
        await fetchServiceBoys(shopId); // Refresh list
      } else {
        print('Failed to update service boy: ${response.statusCode}');
        print('Response body: ${response.body}');
      }
    } catch (e) {
      print('Error updating service boy: $e');
    }
  }


  /// Delete a service boy
  Future<void> deleteServiceBoy(String serviceBoyId, String shopId) async {
    final serviceBoyUri = Uri.parse(ApiConstants.serviceBoyDetails(serviceBoyId));

    try {
      final response = await http.delete(serviceBoyUri);

      if (response.statusCode == 200) {
        await fetchServiceBoys(shopId); // refresh list
      } else {
        print('Failed to delete service boy: ${response.statusCode}');
      }
    } catch (e) {
      print('Error deleting service boy: $e');
    }
  }

  // Select a service boy
  void selectBoy(ServiceBoy boy) {
    _selectedBoy = boy;
    notifyListeners();
  }

  void clearSelection() {
    _selectedBoy = null;
    notifyListeners();
  }
}
