import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/order.dart';
import '../services/auth_service.dart';
import 'woocommerce_service.dart';

class OrderService {
  final AuthService _authService = AuthService();

  /// Holt alle Bestellungen des eingeloggten Benutzers
  Future<List<Order>> getOrders({int perPage = 20, int page = 1}) async {
    try {
      // Versuche zuerst mit JWT Token
      final token = await _authService.getToken();
      
      if (token != null) {
        return await _getOrdersWithToken(token, perPage, page);
      }
      
      // Fallback: Verwende WooCommerce Customer API
      return await _getOrdersWithCredentials(perPage, page);
    } catch (e) {
      throw Exception('Fehler beim Abrufen der Bestellungen: $e');
    }
  }

  Future<List<Order>> _getOrdersWithToken(String token, int perPage, int page) async {
    try {
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wc/v3/orders').replace(
        queryParameters: {
          'per_page': perPage.toString(),
          'page': page.toString(),
          'customer': 'me', // Holt Bestellungen des aktuellen Benutzers
        },
      );

      final response = await http.get(
        uri,
        headers: {
          'Authorization': 'Bearer $token',
        },
      );

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        return data.map((json) => Order.fromJson(json)).toList();
      } else {
        throw Exception('Fehler: ${response.statusCode}');
      }
    } catch (e) {
      // Fallback zur Credentials-Methode
      return await _getOrdersWithCredentials(perPage, page);
    }
  }

  Future<List<Order>> _getOrdersWithCredentials(int perPage, int page) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final username = prefs.getString('username');
      final password = prefs.getString('password');

      if (username == null || password == null) {
        throw Exception('Nicht eingeloggt');
      }

      // Hole Customer ID
      final customerId = await _getCustomerId(username, password);
      if (customerId == null) {
        throw Exception('Kunde nicht gefunden');
      }

      final credentials = base64Encode(utf8.encode('$username:$password'));
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wc/v3/orders').replace(
        queryParameters: {
          'per_page': perPage.toString(),
          'page': page.toString(),
          'customer': customerId.toString(),
        },
      );

      final response = await http.get(
        uri,
        headers: {
          'Authorization': 'Basic $credentials',
        },
      );

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        return data.map((json) => Order.fromJson(json)).toList();
      } else {
        throw Exception('Fehler: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Fehler beim Abrufen der Bestellungen: $e');
    }
  }

  Future<int?> _getCustomerId(String username, String password) async {
    try {
      final credentials = base64Encode(utf8.encode('$username:$password'));
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wc/v3/customers');

      final response = await http.get(
        uri,
        headers: {
          'Authorization': 'Basic $credentials',
        },
      );

      if (response.statusCode == 200) {
        final customers = json.decode(response.body) as List;
        final customer = customers.firstWhere(
          (c) => c['email'] == username || c['username'] == username,
          orElse: () => null,
        );

        return customer != null ? customer['id'] : null;
      }
    } catch (e) {
      print('Fehler beim Abrufen der Customer ID: $e');
    }
    return null;
  }

  /// Holt Details einer einzelnen Bestellung
  Future<Order> getOrder(int orderId) async {
    try {
      final token = await _authService.getToken();
      
      if (token != null) {
        final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wc/v3/orders/$orderId');
        
        final response = await http.get(
          uri,
          headers: {
            'Authorization': 'Bearer $token',
          },
        );

        if (response.statusCode == 200) {
          final data = json.decode(response.body);
          return Order.fromJson(data);
        }
      }
      
      throw Exception('Nicht autorisiert');
    } catch (e) {
      throw Exception('Fehler beim Abrufen der Bestellung: $e');
    }
  }
}

