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 StationService {
  Future<List<dynamic>> fetchStations() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/StationList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching stations 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('StationList API Response Status: ${response.statusCode}');
      debugPrint('StationList API Response Body: ${response.body}');

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

  Future<void> addStation(Map<String, dynamic> stationData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/AddStation');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Adding station 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(stationData),
      );

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

  Future<void> updateStation(Map<String, dynamic> stationData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/EditStation');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Updating station 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(stationData),
      );

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

  Future<void> deleteStation(int id) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/DeleteStation/$id');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Deleting station 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 station. Status code: ${response.statusCode}, Body: ${response.body}');
      }
    } on SocketException {
      throw Exception('No Internet connection. Please check your network.');
    } catch (e) {
      debugPrint('Error deleting station: $e');
      rethrow;
    }
  }
}
