import 'dart:convert';
import 'package:autos/core/constants/api_endpoints.dart';
import 'package:autos/data/models/import_product_model.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/import_product.dart';
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:autos/data/models/user_model.dart';

abstract class ImportsRepository {
  Future<List<ImportProductEntity>> getUserProducts({
    required int page,
    required int pageSize,
    String? category,
    String? subcategory,
  });
}

class ImportsRepositoryImpl implements ImportsRepository {
  final ApiService _apiService;
  final _storage = const FlutterSecureStorage();
  static const _userKey = 'logged_in_user';

  ImportsRepositoryImpl(this._apiService);

  /// ✅ TOKEN LOGIC (UNCHANGED)
  Future<String> getTurn14AccessToken() async {
    final jsonString = await _storage.read(key: _userKey);
    if (jsonString == null) {
      throw Exception("User not found. Please login again.");
    }

    final user = UserModel.fromJson(jsonDecode(jsonString));

    final response = await _apiService.post(
      ApiEndpoints.getToken,
      {"userid": user.id},
    );

    final data = response.data;
    String token;

    if (data["code"] == "TOKEN_UPDATED") {
      token = data["access_token"];
      await _storage.write(key: 'turn14_token', value: token);
    } else if (data["code"] == "TOKEN_VALID") {
      token = data["access_token"];
      await _storage.write(key: 'turn14_token', value: token);
      token = await _storage.read(key: 'turn14_token') ?? '';
      if (token.isEmpty) {
        throw Exception("Token missing in storage");
      }
    } else {
      throw Exception(data["message"]);
    }

    debugPrint("✅ Turn14 Token: $token");
    return token;
  }

  /// ✅✅✅ FINAL: FETCH USER PRODUCTS WITH PAGINATION + FILTERS
  @override
  Future<List<ImportProductEntity>> getUserProducts({
    required int page,
    required int pageSize,
    String? category,
    String? subcategory,
  }) async {
    try {
      final token = await getTurn14AccessToken();
      final userId = await _getUserId();

      /// ✅ CLEAN PARAMS (SKIPS "All")
      final Map<String, dynamic> params = {
        "userid": userId,
        "page": page,
        "pageSize": pageSize,
      };

      if (category != null && category.isNotEmpty && category != "All") {
        params["category"] = category;
      }

      if (subcategory != null &&
          subcategory.isNotEmpty &&
          subcategory != "All") {
        params["subcategory"] = subcategory;
      }

      debugPrint("📡 FETCH USER PRODUCTS");
      debugPrint("➡️ PARAMS: $params");

      final response = await _apiService.get(
        "/api/user-products",
        overrideBaseUrl: "https://ebay.backend.data4autos.com",
        headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
        },
        params: params,
      );

      debugPrint("✅ API STATUS: ${response.statusCode}");
      debugPrint("✅ RAW RESPONSE: ${response.data}");

      if (response.statusCode != 200) {
        throw Exception("Server error: ${response.statusCode}");
      }

      final data = response.data;

      /// ✅ API RETURNS `items`
      if (data is! Map || data["items"] == null) {
        throw Exception("Invalid API structure: 'items' key missing");
      }

      final List list = data["items"];

      debugPrint("✅ TOTAL ITEMS LOADED: ${list.length}");

      return list
          .map(
            (json) => ImportProductModel.fromJson(json).toEntity(),
          )
          .toList();
    } on DioException catch (e) {
      debugPrint("❌ NETWORK ERROR: ${e.response?.data ?? e.message}");
      throw Exception("Network error: ${e.response?.data ?? e.message}");
    } catch (e, st) {
      debugPrint("❌ PARSING ERROR: $e");
      debugPrintStack(stackTrace: st);
      throw Exception("Unexpected error: $e");
    }
  }

  /// ✅ GET USER ID FROM STORAGE
  Future<String> _getUserId() async {
    final jsonString = await _storage.read(key: _userKey);
    if (jsonString == null) {
      throw Exception("User not found");
    }

    final user = UserModel.fromJson(jsonDecode(jsonString));
    return user.id;
  }
}
