import 'dart:convert';

import 'package:autos/data/models/turn14_model.dart';
import 'package:autos/data/repositories/turn14_repository_impl.dart';
import 'package:autos/data/sources/remote/api_service.dart';
import 'package:autos/domain/entities/turn14.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/legacy.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

/// ------------------------------------------------------------
///  Service Providers
/// ------------------------------------------------------------

final turn14ApiServiceProvider = Provider<ApiService>(
  (ref) => ApiService(),
);

final turn14RepositoryProvider = Provider<Turn14RepositoryImpl>(
  (ref) => Turn14RepositoryImpl(ref.read(turn14ApiServiceProvider)),
);

/// ------------------------------------------------------------
///  Turn14 Notifier
/// ------------------------------------------------------------

class Turn14Notifier extends StateNotifier<AsyncValue<Turn14Entity?>> {
  final Turn14RepositoryImpl repository;
  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  static const String _turn14StorageKey = "turn14_credentials";

  Turn14Notifier(this.repository) : super(const AsyncValue.data(null));

  // ------------------------------------------------------------
  // Save Turn14 credentials (API + local)
  // ------------------------------------------------------------
  Future<void> saveCredentials({
    required String userId,
    required String clientId,
    required String clientSecret,
  }) async {
    state = const AsyncValue.loading();

    try {
      final Turn14Entity entity = await repository.save(
        userId: userId,
        clientId: clientId,
        clientSecret: clientSecret,
      );

      // Convert entity → model (for persistence)
      final model = Turn14StatusModel(
        userId: entity.userId,
        hasCredentials: entity.hasCredentials,
        clientId: entity.clientId,
        clientSecret: entity.clientSecret,
        accessToken: entity.accessToken,
        expiresIn: entity.expiresIn,
        code: entity.code,
        message: entity.message,
      );

      await _storage.write(
        key: _turn14StorageKey,
        value: jsonEncode(model.toJson()),
      );

      state = AsyncValue.data(entity);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  // ------------------------------------------------------------
  // Load Turn14 from LOCAL storage
  // ------------------------------------------------------------
  Future<void> loadSavedCredentials() async {
    try {
      final saved = await _storage.read(key: _turn14StorageKey);
      if (saved == null) {
        state = const AsyncValue.data(null);
        return;
      }

      final decoded = jsonDecode(saved);
      final model = Turn14StatusModel.fromJson(decoded);

      final entity = Turn14Entity(
        code: model.code ?? '',
        message: model.message ?? '',
        userId: model.userId,
        hasCredentials: model.hasCredentials,
        clientId: model.clientId,
        clientSecret: model.clientSecret,
        accessToken: model.accessToken,
        expiresIn: model.expiresIn,
      );

      state = AsyncValue.data(entity);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  // ------------------------------------------------------------
  // Load Turn14 status from API + persist locally
  // ------------------------------------------------------------
  Future<void> loadTurn14Status(String userId) async {
    state = const AsyncValue.loading();

    try {
      final status = await repository.status(userId);
      // Turn14StatusEntity

      if (status.hasCredentials == true) {
        final entity = Turn14Entity(
          code: '',
          message: '',
          userId: status.userId,
          hasCredentials: status.hasCredentials,
          clientId: status.clientId,
          clientSecret: status.clientSecret,
          accessToken: status.accessToken,
          expiresIn: status.expiresIn?.toString(),
        );

        final model = Turn14StatusModel(
          userId: entity.userId,
          hasCredentials: entity.hasCredentials,
          clientId: entity.clientId,
          clientSecret: entity.clientSecret,
          accessToken: entity.accessToken,
          expiresIn: entity.expiresIn,
          code: entity.code,
          message: entity.message,
        );

        await _storage.write(
          key: _turn14StorageKey,
          value: jsonEncode(model.toJson()),
        );

        state = AsyncValue.data(entity);
      } else {
        await clear();
      }
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  // ------------------------------------------------------------
  // Clear Turn14 data (logout / user switch)
  // ------------------------------------------------------------
  Future<void> clear() async {
    await _storage.delete(key: _turn14StorageKey);
    state = const AsyncValue.data(null);
  }
}

/// ------------------------------------------------------------
///  Riverpod Provider
/// ------------------------------------------------------------

final turn14Provider =
    StateNotifierProvider<Turn14Notifier, AsyncValue<Turn14Entity?>>(
  (ref) => Turn14Notifier(ref.read(turn14RepositoryProvider)),
);
