import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/user.dart';
import 'woocommerce_service.dart';

class AuthService {
  static const String _userKey = 'user_data';
  static const String _tokenKey = 'auth_token';

  /// Meldet einen Benutzer an
  /// 
  /// Verwendet die WordPress REST API für die Authentifizierung
  Future<User?> login(String username, String password) async {
    try {
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/jwt-auth/v1/token');
      
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'username': username,
          'password': password,
        }),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        
        if (data['token'] != null) {
          // Speichere Token
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString(_tokenKey, data['token']);
          
          // Hole Benutzerdaten
          final user = await getUserData(data['token']);
          
          if (user != null) {
            await saveUser(user);
            return user;
          }
        }
      } else if (response.statusCode == 403) {
        // JWT Auth Plugin nicht installiert, verwende alternative Methode
        return await _loginAlternative(username, password);
      }
      
      return null;
    } catch (e) {
      print('Login-Fehler: $e');
      return null;
    }
  }

  /// Alternative Login-Methode über WooCommerce REST API
  Future<User?> _loginAlternative(String username, String password) async {
    try {
      // Verwende Basic Auth mit WooCommerce API
      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) {
        // Suche nach dem Benutzer mit dieser E-Mail/Username
        final customers = json.decode(response.body) as List;
        final customer = customers.firstWhere(
          (c) => c['email'] == username || c['username'] == username,
          orElse: () => null,
        );

        if (customer != null) {
          final user = User.fromJson(customer);
          await saveUser(user);
          // Speichere Credentials für spätere API-Calls
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString('username', username);
          await prefs.setString('password', password); // In Produktion verschlüsseln!
          return user;
        }
      }
      
      return null;
    } catch (e) {
      print('Alternative Login-Fehler: $e');
      return null;
    }
  }

  /// Holt Benutzerdaten mit Token
  Future<User?> getUserData(String token) async {
    try {
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wp/v2/users/me');
      
      final response = await http.get(
        uri,
        headers: {
          'Authorization': 'Bearer $token',
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        return User.fromJson(data);
      }
      
      return null;
    } catch (e) {
      print('Fehler beim Abrufen der Benutzerdaten: $e');
      return null;
    }
  }

  /// Speichert Benutzerdaten lokal
  Future<void> saveUser(User user) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_userKey, json.encode(user.toJson()));
  }

  /// Lädt gespeicherten Benutzer
  Future<User?> getSavedUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userJson = prefs.getString(_userKey);
      
      if (userJson != null) {
        final userData = json.decode(userJson);
        return User.fromJson(userData);
      }
      
      return null;
    } catch (e) {
      print('Fehler beim Laden des gespeicherten Benutzers: $e');
      return null;
    }
  }

  /// Prüft ob Benutzer eingeloggt ist
  Future<bool> isLoggedIn() async {
    final user = await getSavedUser();
    return user != null;
  }

  /// Meldet den Benutzer ab
  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_userKey);
    await prefs.remove(_tokenKey);
    await prefs.remove('username');
    await prefs.remove('password');
  }

  /// Holt das gespeicherte Token
  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// Registriert einen neuen Benutzer
  Future<Map<String, dynamic>> register({
    required String email,
    required String username,
    required String password,
    String? firstName,
    String? lastName,
  }) async {
    try {
      // Versuche WordPress REST API
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wp/v2/users');
      
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'username': username,
          'email': email,
          'password': password,
          'first_name': firstName ?? '',
          'last_name': lastName ?? '',
        }),
      );

      if (response.statusCode == 201) {
        final data = json.decode(response.body);
        return {'success': true, 'user_id': data['id']};
      } else {
        final error = json.decode(response.body);
        return {
          'success': false,
          'message': error['message'] ?? 'Registrierung fehlgeschlagen',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': 'Fehler bei der Registrierung: $e',
      };
    }
  }

  /// Sendet Passwort-Reset-E-Mail
  Future<Map<String, dynamic>> requestPasswordReset(String email) async {
    try {
      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/bdpwr/v1/reset-password');
      
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: json.encode({'email': email}),
      );

      if (response.statusCode == 200) {
        return {'success': true, 'message': 'Reset-Link wurde per E-Mail gesendet'};
      } else {
        // Fallback: WordPress Standard
        final uri2 = Uri.parse('${WooCommerceService.baseUrl}/wp-login.php?action=lostpassword');
        final response2 = await http.post(
          uri2,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          body: 'user_login=$email',
        );

        return {
          'success': response2.statusCode == 200,
          'message': 'Bitte prüfe deine E-Mails für den Reset-Link',
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': 'Fehler beim Anfordern des Passwort-Resets: $e',
      };
    }
  }

  /// Aktualisiert Benutzerprofil
  Future<User?> updateProfile({
    required String firstName,
    required String lastName,
    String? email,
    String? displayName,
  }) async {
    try {
      final token = await getToken();
      if (token == null) return null;

      final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wp/v2/users/me');
      
      final body = <String, dynamic>{
        'first_name': firstName,
        'last_name': lastName,
      };
      
      if (email != null) body['email'] = email;
      if (displayName != null) body['name'] = displayName;

      final response = await http.post(
        uri,
        headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
        },
        body: json.encode(body),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final user = User.fromJson(data);
        await saveUser(user);
        return user;
      }
      
      return null;
    } catch (e) {
      print('Fehler beim Aktualisieren des Profils: $e');
      return null;
    }
  }
}

