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 ProductService {
  Future<List<dynamic>> fetchProducts() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/ProductList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching products 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);

      debugPrint('ProductList API Response Status: ${response.statusCode}');
      debugPrint('ProductList API Response Body: ${response.body}');

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

  Future<List<dynamic>> fetchManufacturers() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/ManufacturerList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching manufacturers 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 manufacturers. Status: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection.');
    } catch (e) {
      debugPrint('Error fetching manufacturers: $e');
      rethrow;
    }
  }

  Future<void> addProduct(Map<String, dynamic> productData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/AddProduct');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Adding product to: $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,
        body: jsonEncode(productData),
      );

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

  Future<void> updateProduct(Map<String, dynamic> productData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/EditProduct');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Updating product at: $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,
        body: jsonEncode(productData),
      );

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

  Future<void> deleteProduct(int id) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/DeleteProduct/$id');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Deleting product at: $uri");

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

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

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