import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:inventory_system/services/api_service.dart';
import 'package:inventory_system/services/session_manager.dart';

class ItemService {
  Future<List<dynamic>> fetchItems() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/ItemList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching items from: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);

      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : [];
      } else {
        throw Exception('Failed to load items. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching items: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>> getItem(String id) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/GetItem/$id');
    final cookie = SessionManager.instance.getCookie();

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      // The Vue app uses POST for GetItem/{id}
      final response = await http.post(uri, headers: headers);

      if (response.statusCode == 200) {
        return response.body.isNotEmpty ? jsonDecode(response.body) : {};
      } else {
        throw Exception('Failed to get item. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error getting item: $e');
      rethrow;
    }
  }

  Future<void> updateItemQuantity(Map<String, dynamic> data) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/UpdateItemQuantity');
    final cookie = SessionManager.instance.getCookie();

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(
        uri,
        headers: headers,
        body: jsonEncode(data),
      );

      if (response.statusCode != 200) {
        throw Exception('Failed to update item quantity. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error updating item quantity: $e');
      rethrow;
    }
  }

  Future<void> addItem(Map<String, dynamic> itemData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/AddItem');
    final cookie = SessionManager.instance.getCookie();

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(
        uri,
        headers: headers,
        body: jsonEncode(itemData),
      );

      if (response.statusCode != 200) {
        throw Exception('Failed to add item. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error adding item: $e');
      rethrow;
    }
  }

  Future<void> updateItem(Map<String, dynamic> itemData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/EditItem');
    final cookie = SessionManager.instance.getCookie();

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(
        uri,
        headers: headers,
        body: jsonEncode(itemData),
      );

      if (response.statusCode != 200) {
        throw Exception('Failed to update item. Status: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error updating item: $e');
      rethrow;
    }
  }

  Future<void> deleteItem(int id) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/DeleteItem/$id');
    final cookie = SessionManager.instance.getCookie();

    final Map<String, String> headers = {
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.delete(uri, headers: headers);

      if (response.statusCode != 200) {
        throw Exception('Failed to delete item. Status: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error deleting item: $e');
      rethrow;
    }
  }
}
