import 'dart:convert';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/controller/functions/encrypt_decrypt.dart';

import '../../constant/box_name.dart';
import '../../constant/char_map.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../../print.dart';
import 'crud.dart';

class SecureStorage {
  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  void saveData(String key, value) async {
    await _storage.write(key: key, value: value);
  }

  Future<String?> readData(String boxName) async {
    final String? value = await _storage.read(key: boxName);
    return value;
  }
}

const List<String> keysToFetch = [
  'serverPHP',
  'seferAlexandriaServer',
  'seferPaymentServer',
  'seferCairoServer',
  'seferGizaServer',
];

class AppInitializer {
  List<Map<String, dynamic>> links = [];

  Future<void> initializeApp() async {
    if (box.read(BoxName.jwt) == null) {
      await LoginDriverController().getJWT();
    } else {
      String token = r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0];
      bool isTokenValid = false;
      try {
        final parts = token.split('.');
        if (parts.length == 3) {
          String payload = parts[1];
          switch (payload.length % 4) {
            case 2: payload += '=='; break;
            case 3: payload += '='; break;
          }
          final decoded = jsonDecode(utf8.decode(base64Url.decode(payload)));
          final exp = decoded['exp'];
          if (exp != null) {
            isTokenValid = DateTime.now().millisecondsSinceEpoch < (exp * 1000 - 30000);
          }
        }
      } catch (_) {}
      if (!isTokenValid) {
        await LoginDriverController().getJWT();
      }
    }

    // await getKey();
  }

  Future<void> getAIKey(String key1) async {
    var res =
        await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});

    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      final rawValue = d[key1].toString();

      // ✅ اكتبها في storage
      await storage.write(key: key1, value: rawValue);

      await Future.delayed(Duration.zero);
    }
  }

  Future<void> getKey() async {
    try {
      var res =
          await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
      if (res != 'failure') {
        links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);

        await box.write(BoxName.locationName, links);
        await box.write(BoxName.basicLink, (links[0]['server_link']));
        await box.write(links[2]['name'], (links[2]['server_link']));
        await box.write(links[1]['name'], (links[3]['server_link']));
        await box.write(links[3]['name'], (links[1]['server_link']));
        await box.write(BoxName.paymentLink, (links[4]['server_link']));
      }
    } catch (e) {}
  }
}
